Fillng out some exercise program thing

This commit is contained in:
Dan Buch 2020-11-27 11:45:08 -05:00
parent 03fe3dc177
commit 1d602cb1cd
Signed by: meatballhat
GPG Key ID: 9685130D8B763EA7
4 changed files with 87 additions and 3 deletions

4
.gitignore vendored
View File

@ -2,7 +2,5 @@
*.log
*env
.dep
/guessing_game/target/
/hello_cargo/target/
**/target/
/hello_world/main
/scarytxt/target/

5
variables/Cargo.lock generated Normal file
View File

@ -0,0 +1,5 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "variables"
version = "0.1.0"

9
variables/Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[package]
name = "variables"
version = "0.1.0"
authors = ["Dan Buch <dan@meatballhat.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

72
variables/src/main.rs Normal file
View File

@ -0,0 +1,72 @@
use std::env;
use std::process;
fn main() {
let mut command = String::new();
let mut command_args = Vec::<String>::new();
for (i, arg) in env::args().enumerate() {
match i {
0 => continue,
1 => {
command = arg;
continue;
}
_ => command_args.push(arg.as_str().to_string()),
}
}
match command.as_str() {
"tc" => {
if command_args.len() < 1 {
println!("ERROR: missing a value to convert");
process::exit(1);
}
temp_convert(command_args[0].as_str().to_string())
}
"rx" => redefine_x(),
"help" | _ => show_help(),
}
}
fn show_help() {
println!("Usage: variables <command> [command_args]");
println!();
println!("The value for <command> may be one of:");
println!(" tc - convert temperatures between Fahrenheit and Celsius");
println!(" rx - redefine x");
println!();
}
fn redefine_x() {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
}
fn temp_convert(to_convert: String) {
let to_convert = to_convert.to_lowercase();
if to_convert.ends_with("c") {
let c: f32 = to_convert
.trim_end_matches('c')
.parse()
.expect("failed to parse temperature");
println!("{}F", temp_convert_c2f(c));
} else if to_convert.ends_with("f") {
let f: f32 = to_convert
.trim_end_matches('f')
.parse()
.expect("failed to parse temperature");
println!("{}C", temp_convert_f2c(f));
} else {
println!("What are we supposed to do to {:?}?", to_convert);
}
}
fn temp_convert_c2f(c: f32) -> f32 {
(c * (9.0 / 5.0)) + 32.0
}
fn temp_convert_f2c(f: f32) -> f32 {
(f - 32.0) * (5.0 / 9.0)
}