編寫一個(gè)貨幣兌換程序炉媒。具體來(lái)說(shuō)线召,是將歐元兌換成美元。
提示輸入手動(dòng)的歐元數(shù)俐载,以及歐元的當(dāng)前匯率蟹略。打印可以兌換的美元數(shù)。
貨幣兌換的公式為:
其中
- amountto 是美元
- amountfrom 是歐元數(shù)
- ratefrom 是歐元的當(dāng)前匯率
- rateto 是美元的當(dāng)前匯率
示例輸出
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.
約束
- 注意小數(shù)部分遏佣,不足1美分的向上取整挖炬。
- 使用單條輸出語(yǔ)句。
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
);
}
// 從控制臺(tái)讀取數(shù)據(jù)
fn read_from_console(notice: String) -> f32 {
println!("{}", notice);
loop {
let mut amountfrom = String::new();
// 控制臺(tái)輸入歐元金額
std::io::stdin().read_line(&mut amountfrom).unwrap();
// 注意要對(duì)輸入的字符串進(jìn)行trim()操作后再做類型轉(zhuǎn)換
if let Ok(res) = amountfrom.trim().parse::<f32>() {
return res;
} else {
println!("輸入的數(shù)據(jù)類型錯(cuò)誤:{}", amountfrom);
}
}
}
結(jié)果:
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.