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

如何在C#圆面积计算程序中用if实现输入合法性校验

给C#圆面积计算代码添加输入校验

你的核心需求是通过输入校验避免非数字输入导致的程序错误,这里我们用int.TryParse方法配合if语句来实现——它能安全地尝试将输入字符串转为整数,同时返回是否转换成功的布尔值,完美适配你的校验需求。

修改后的完整代码如下:

using System;

namespace Jay_trycode
{
    class Program
    {
        static void Main(string[] args)
        {
            // 计算圆面积程序
            int radius;
            double area;

            Console.Write("*****Area of the Circle*****");
            Console.WriteLine("\n\nPlease input the radius: ");
            string input = Console.ReadLine();

            // 输入校验:尝试将输入转为整数
            if (int.TryParse(input, out radius))
            {
                // 转换成功,计算并输出面积
                area = 3.1415 * radius * radius;
                Console.Write("\nThe Area of the Circle is: " + Math.Round(area, 2));
            }
            else
            {
                // 转换失败,输出错误提示
                Console.WriteLine("Invalid, please enter a valid value.");
            }

            // 停留控制台方便查看结果
            Console.ReadLine();
        }
    }
}

关键修改点说明:

  • 先用string input接收用户输入的原始字符串,避免直接转换非数字时抛出异常
  • int.TryParse(input, out radius):第一个参数是输入字符串,第二个参数是输出的转换结果;方法返回true表示转换成功,false表示失败
  • 通过if-else分支分别处理「有效输入计算面积」和「无效输入提示错误」的逻辑
  • 额外添加最后一行Console.ReadLine(),防止程序运行后直接退出,方便查看输出结果

如果需要支持小数半径(比如输入2.5这类数值),只需把int radius改成double radius,同时将int.TryParse替换为double.TryParse即可,公式部分无需改动。

内容的提问来源于stack exchange,提问作者Jay Delos Santos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:01:27