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

C#控制台输入整数统计偶数问题及代码报错求助

解决C#控制台输入整数统计偶数问题

需求说明

用户从控制台逐个输入任意数量的整数,输入"x"时程序停止,统计并输出输入中的偶数数量。

示例

输入:

2
5
8
4
1
6
9
2
5
x

输出:

5

现有代码及错误信息

用户代码

using System;

public class TestNumericDataTypesOperations
{
    public static void Main()
    {

        string[] a = new string[100];

        int b=0;
        int total = 0;


        for (int i = 0; i < a.Length; i++)
        {
            a[i] = Console.ReadLine();
            int b = int.Parse(a);
            if (b % 2 == 0)

                total++;


            if (a[i] == "x")
            {
                break;
            }
            Console.WriteLine(total);
        }

    }
}

报错详情

  • 第17行(int b = int.Parse(a);):CS1503(参数类型不匹配,传入数组而非数组元素)、CS0136(重复声明变量b,与外部作用域的b冲突)
  • 第10行(int b=0;):CS0219(变量b已定义但未被使用)
  • 第16行(a[i] = Console.ReadLine();):CS8601(Console.ReadLine()可能返回null,存在空引用赋值风险)

修复方案及优化代码

核心修复点

  1. 解决变量作用域冲突:移除循环内重复声明的int关键字,复用外部变量;修正int.Parse的参数为数组元素a[i]
  2. 处理空引用:增加null输入的判断逻辑
  3. 修正业务逻辑:先判断输入是否为"x"再解析整数,避免"x"被当成整数解析报错;将结果输出移到循环结束后,而非每次循环都输出
  4. 增强健壮性:用int.TryParse替代int.Parse,处理非整数输入的情况;用while(true)替代固定长度数组循环,取消输入数量限制

修复后的最终代码

using System;

public class TestNumericDataTypesOperations
{
    public static void Main()
    {
        int totalEven = 0;

        while (true)
        {
            string input = Console.ReadLine();
            
            // 处理输入为空的情况
            if (input == null)
            {
                break;
            }

            // 输入x(不区分大小写)时退出循环
            if (input.Trim().Equals("x", StringComparison.OrdinalIgnoreCase))
            {
                break;
            }
            
            // 尝试解析输入为整数,成功后判断是否为偶数
            if (int.TryParse(input, out int number))
            {
                if (number % 2 == 0)
                {
                    totalEven++;
                }
            }
            else
            {
                Console.WriteLine("请输入有效的整数或x");
            }
        }

        // 输出最终统计的偶数数量
        Console.WriteLine(totalEven);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 18:22:37