我在C#中需要解决这个问题:用户从控制台输入整数(不是固定数量的int,而是无限数量的int,想多少就多少),当用户输入值“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 行收到错误 CS1503 和 CS0136 (
int b = int.Parse(a);
),在第 10 行收到警告 CS0219 (int b=0;
),在第 16 行收到警告 CS8601 (a[i] = Console.ReadLine();
)。
谢谢!
第一期:
int.Parse(a);
a
这里是一个数组,而不是字符串。您需要改用 a
中的特定条目。
但是编译器忽略了一个更糟糕的问题:您在之前检查输入是否为
x
执行此操作,这意味着您期望在这里至少看到一次非整数值。当程序运行时,这将导致编译器无法预料的异常。您应该查看 int.TryParse()
,然后将此部分移至 after 检查用户是否要退出。
然后我们看到了这一行的警告:
int b = 0;
这里的问题是这个变量从未被使用过。相反,在循环内部,变量被重新声明:
int b = int.Parse(a);
。从后面的行中删除 int
,或者(根据偏好)完全删除第一行。
最后我们收到了该行的警告:
a[i] = Console.ReadLine();
这与用于可空引用检查的 C# 新功能有关。
Console.Readline()
方法比这些检查要古老得多,并且由于历史原因,不会将其结果标记为非空。您可以完全关闭这些检查(不推荐)或添加特殊的null-forgiveness运算符:a[i] = Console.ReadLine()!;
这一行还有最后一个问题:
Console.WriteLine(total);
该行仍在循环内,这意味着它将重写每个条目的总计。您可能只想在循环之后之后执行此操作一次。
但是为了好玩,因为我们不再使用原始输入,所以我会这样写(不需要数组):
public static void Main()
{
int total = 0;
string input;
while( (input = Console.ReadLine()) != "x")
{
if (int.TryParse(input, out int i) && i % 2 == 0)
total++;
}
Console.WriteLine(total);
}
// true, if we read an integer value (result)
// false, if user wants to stop adding items
private static bool TryReadInt(out int result) {
result = 0;
// We keep asking user until
while (true) {
string input = Console.ReadLine();
// user writes "x"
if (input.Trim() == "x") {
result = 0;
return false;
}
// Or provide a valid integer value
if (int.TryParse(input, out result))
return true;
Console.WriteLine("Not a valid integer, please, try again");
}
}
然后我们可以像这样实现Main
例程(注意,我们不需要任何集合,因为我们要做的只是计数,而不是提供所有偶数):
public static void Main() {
int total = 0;
while (true) {
// We want just one current item, not a collection
if (!TryReadInt(out var item))
break;
if (item % 2 == 0)
total += 1;
}
Console.WriteLine(total);
}