You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rust中实现浮点数字输入的循环验证?

解决Rust BMI程序输入非数字崩溃的问题

原程序在用户输入非数字内容时崩溃,核心原因是使用parse().expect(...)在解析失败时直接触发panic。要实现"输入无效时重新提示"的效果,我们可以通过循环结合match处理解析结果,直到获取有效的浮点数值。

优化后的完整代码

use std::io;

fn main() {
    println!("***Rust BMI***");

    let weight = get_valid_float_input("Inform your weight: ");
    println!("Your weight is {}kg", weight);

    let height = get_valid_float_input("Inform your height: ");
    println!("Your height is {}m", height);

    println!("Your bmi is {}", bmi(weight, height));
    println!("You are: {}", bmi_res(weight, height));
}

// 通用函数:持续获取有效的浮点输入,直到用户输入正确
fn get_valid_float_input(prompt: &str) -> f32 {
    loop {
        let mut input = String::new();
        println!("{}", prompt);
        io::stdin()
            .read_line(&mut input)
            .expect("Failed to read input");
        
        // 匹配解析结果:成功则返回数值,失败则提示重新输入
        match input.trim().parse() {
            Ok(num) => return num,
            Err(_) => println!("Invalid input, please enter a valid number."),
        }
    }
}

fn bmi(weight: f32, height: f32) -> f32 {
    weight / (height * height)
}

fn bmi_res(weight: f32, height: f32) -> &'static str {
    let index = weight / height.powi(2);
    match index {
        index if index <= 18.5 => "Underweight",
        index if index <= 25.0 => "Normal",
        index if index <= 30.0 => "Overweight",
        _ => "Obese",
    }
}

关键优化说明

  • 提取get_valid_float_input通用函数,避免重复编写输入处理逻辑,简化主函数结构。
  • 用loop循环实现持续输入请求,只有当parse成功返回Ok(num)时才退出循环,否则打印错误提示并继续请求输入。
  • 移除原代码中多余的变量初始化操作,直接通过函数返回有效数值,代码更简洁。

Rust中没有直接的is_float()方法,判断字符串是否为有效浮点数的核心逻辑就是通过parse方法尝试转换,失败时返回Err,我们通过match捕获这个结果即可完成输入校验。

内容的提问来源于stack exchange,提问作者Jovane Rocha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:30:52