编写一个货币兑换程序。具体来说,是将欧元兑换成美元。
提示输入手动的欧元数,以及欧元的当前汇率。打印可以兑换的美元数。
货币兑换的公式为:
其中
- amountto 是美元
- amountfrom 是欧元数
- ratefrom 是欧元的当前汇率
- rateto 是美元的当前汇率
示例输出
How mang euros are you exchanging? 81
What is the exchange rate? 137.51
81 euros at an exchange rate of 137.51 is
111.38 U.S. dollars.
约束
- 注意小数部分,不足1美分的向上取整。
- 使用单条输出语句。
fn main(){
let amountfrom = read_from_console(String::from("How mang euros are you exchanging?"));
println!("euros is:{}", amountfrom);
let ratefrom = read_from_console(String::from("What is the exchange rate?"));
println!("exchange rate is:{}", ratefrom);
const RATE_TO: f32 = 100.0;
let result = (amountfrom * ratefrom).ceil() / RATE_TO;
println!(
"{} euros at an exchange rate of {} is {} U.S. dollars.",
amountfrom, ratefrom, result
);
}
// 从控制台读取数据
fn read_from_console(notice: String) -> f32 {
println!("{}", notice);
loop {
let mut amountfrom = String::new();
// 控制台输入欧元金额
std::io::stdin().read_line(&mut amountfrom).unwrap();
// 注意要对输入的字符串进行trim()操作后再做类型转换
if let Ok(res) = amountfrom.trim().parse::<f32>() {
return res;
} else {
println!("输入的数据类型错误:{}", amountfrom);
}
}
}
结果:
How mang euros are you exchanging?
81
euros is:81
What is the exchange rate?
137.51
exchange rate is:137.51
81 euros at an exchange rate of 137.51 is 111.39 U.S. dollars.