Do the fibs

cat-town
Dan Buch 4 years ago
parent 1d602cb1cd
commit e3122519df
Signed by: meatballhat
GPG Key ID: 9685130D8B763EA7

@ -18,11 +18,24 @@ fn main() {
match command.as_str() { match command.as_str() {
"tc" => { "tc" => {
if command_args.len() < 1 { if command_args.len() < 1 {
println!("ERROR: missing a value to convert"); eprintln!("ERROR: missing a value to convert");
process::exit(1); process::exit(1);
} }
temp_convert(command_args[0].as_str().to_string()) temp_convert(command_args[0].as_str().to_string())
} }
"fib" => {
if command_args.len() < 1 {
eprintln!("ERROR: missing a value to fib");
process::exit(1);
}
let n: u64 = command_args[0]
.parse()
.expect("could not parse value to fib");
if n >= 40 {
eprintln!("WARN: this might take a while");
}
fib_n(n)
}
"rx" => redefine_x(), "rx" => redefine_x(),
"help" | _ => show_help(), "help" | _ => show_help(),
} }
@ -32,6 +45,7 @@ fn show_help() {
println!("Usage: variables <command> [command_args]"); println!("Usage: variables <command> [command_args]");
println!(); println!();
println!("The value for <command> may be one of:"); println!("The value for <command> may be one of:");
println!(" fib - generate Nth Fibonacci number");
println!(" tc - convert temperatures between Fahrenheit and Celsius"); println!(" tc - convert temperatures between Fahrenheit and Celsius");
println!(" rx - redefine x"); println!(" rx - redefine x");
println!(); println!();
@ -59,7 +73,7 @@ fn temp_convert(to_convert: String) {
.expect("failed to parse temperature"); .expect("failed to parse temperature");
println!("{}C", temp_convert_f2c(f)); println!("{}C", temp_convert_f2c(f));
} else { } else {
println!("What are we supposed to do to {:?}?", to_convert); eprintln!("ERROR: What are we supposed to do to {:?}?", to_convert);
} }
} }
@ -70,3 +84,15 @@ fn temp_convert_c2f(c: f32) -> f32 {
fn temp_convert_f2c(f: f32) -> f32 { fn temp_convert_f2c(f: f32) -> f32 {
(f - 32.0) * (5.0 / 9.0) (f - 32.0) * (5.0 / 9.0)
} }
fn fib_n(n: u64) {
println!("{}", fib_up_to(n));
}
fn fib_up_to(n: u64) -> u64 {
match n {
0 => 0,
1 => 1,
_ => fib_up_to(n - 1) + fib_up_to(n - 2),
}
}

Loading…
Cancel
Save