Do the fibs

This commit is contained in:
Dan Buch 2020-11-27 15:27:35 -05:00
parent 1d602cb1cd
commit e3122519df
Signed by: meatballhat
GPG Key ID: 9685130D8B763EA7

View File

@ -18,11 +18,24 @@ fn main() {
match command.as_str() {
"tc" => {
if command_args.len() < 1 {
println!("ERROR: missing a value to convert");
eprintln!("ERROR: missing a value to convert");
process::exit(1);
}
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(),
"help" | _ => show_help(),
}
@ -32,8 +45,9 @@ 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!(" fib - generate Nth Fibonacci number");
println!(" tc - convert temperatures between Fahrenheit and Celsius");
println!(" rx - redefine x");
println!();
}
@ -59,7 +73,7 @@ fn temp_convert(to_convert: String) {
.expect("failed to parse temperature");
println!("{}C", temp_convert_f2c(f));
} 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 {
(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),
}
}