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

C#身高判断逻辑异常:输入小于1.5的数值仍提示可进入如何修复

问题根因

  • 区域文化导致的解析错误:float.Parse()默认读取当前操作系统的区域配置解析数值,如果你的系统使用逗号,作为小数点分隔符,点.作为千位分隔符,输入的1.4这类带点的数值会被错误解析为14,自然会命中height > 1.5的判断逻辑,输出错误结果。
  • 浮点数字面量类型不匹配:判断条件中的1.5默认是double类型,和float类型的height比较时会发生隐式类型转换,部分场景下会出现精度丢失导致判断结果不符合预期。
  • 额外问题:代码没有做输入合法性校验,用户输入非数值内容时会直接抛出异常崩溃。

修复方案

  1. 解析身高时指定使用不变文化(InvariantCulture) 作为解析规则,固定用点.作为小数点分隔符,消除区域差异的影响。
  2. 将判断条件中的1.5改为float类型字面量1.5f,避免跨类型比较的精度问题。
  3. 增加输入合法性校验,避免非法输入导致程序崩溃。

修复后完整代码

using System;
using System.Globalization;

namespace Tarea_C_
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Write your age: ");
            // 年龄输入校验
            if (!int.TryParse(Console.ReadLine(), out int age) || age < 0)
            {
                Console.WriteLine("Invalid age input");
                return;
            }

            if (age >= 18)
            {
                Console.Write("Write your height: ");
                // 身高输入校验+固定区域格式解析
                if (!float.TryParse(Console.ReadLine(), NumberStyles.Float, CultureInfo.InvariantCulture, out float height))
                {
                    Console.WriteLine("Invalid height input");
                    return;
                }

                if (height > 1.5f)
                {
                    Console.WriteLine("Come in");
                }
                else
                {
                    Console.WriteLine("Stay out");
                }
            }
            else
            {
                Console.WriteLine("Stay out");
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Miguel Rosales

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:06:04