简村消零派(洛九幽)

Rust每日练习---货币换算

2021-06-28  本文已影响0人  梦想实现家_Z

编写一个货币兑换程序。具体来说,是将欧元兑换成美元。

提示输入手动的欧元数,以及欧元的当前汇率。打印可以兑换的美元数。

货币兑换的公式为:


image-20210628112823364.png

其中

示例输出

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.

约束

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.
上一篇下一篇

猜你喜欢

热点阅读