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

C#控制台输入小数报错:输入整数正常、小数触发错误求助

问题分析与解决方案

核心错误原因

输入小数时报错,是因为代码里用了Int32.Parse(radius)——这个方法只能解析整数格式的字符串,当输入带小数点的数值时,它无法识别,直接抛出格式异常。

另外代码里还有个明显错误:计算结果的变量名和输出语句里的变量名不匹配,比如你计算的圆周长存在RLG变量里,但输出时写的是CLL,运行时会提示变量未定义。

修正步骤

  1. 替换整数解析为浮点数解析:把Int32.Parse(radius)改成Double.Parse(radius),这样就能处理小数输入了。
  2. 统一变量名:把输出语句里的变量名改成和计算时一致的,保证对应关系正确。
  3. 添加输入验证(可选但推荐):用Double.TryParse替代直接解析,输入非数值内容时不会崩溃,还能给用户提示。

修正后的完整代码

using System;

namespace Circle
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Radius R = ");
            string radiusInput = Console.ReadLine();
            
            // 验证输入是否为有效的浮点数
            if (!double.TryParse(radiusInput, out double radius))
            {
                Console.WriteLine("请输入有效的数值(整数或小数)");
                return;
            }
            
            const double pi = 3.1415926;
            double circleCircumference = radius * 2 * pi;
            double circleArea = Math.Pow(radius, 2) * pi;
            double sphereSurfaceArea = Math.Pow(radius, 2) * 4 * pi;
            double sphereVolume = Math.Pow(radius, 3) * 4 * pi / 3;

            Console.WriteLine("circle line length: " + circleCircumference);
            Console.WriteLine("circle surface size: " + circleArea);
            Console.WriteLine("sphere surface size: " + sphereSurfaceArea);
            Console.WriteLine("sphere volume: " + sphereVolume);
        }
    }
}

代码说明

  • 用double.TryParse做输入验证,用户输入无效内容时会友好提示,避免程序崩溃。
  • 把num1改成语义化的pi,并用const修饰,表明这是常量。
  • 变量名改用更清晰的英文命名,方便后续维护,也和输出描述对应起来。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:22:45