0
      string num;
            num = Console.ReadLine();
            Console.WriteLine(num);
            switch (num)
            {case 1:
            Console.WriteLine(one);

我正在尝试执行 ac# 项目,您可以在其中键入一个从 1 到 100 的数字,然后您会看到它的写入版本。

4

2 回答 2

1

The variable num is a string. But you're trying to compare it with an integer here:

case 1:

The quickest solution would be to compare it with a string:

case "1":

Alternatively, and possibly as a learning experience for you, you may want to try converting num to an int. Take a look at int.TryParse for that. An example might look like this:

string num = Console.ReadLine();
int numValue = 0;
if (!int.TryParse(num, out numValue)) {
    // The value entered was not an integer.  Perhaps show the user an error message?
}
于 2019-12-07T17:53:59.137 回答
-1

您提到只想打印 1 到 100 之间的数字。这个版本就是这样做的。

var consoleResponse = Console.ReadLine();

if (int.TryParse(consoleResponse, out int parsedValue) 
        && parsedValue >= 1 
        && parsedValue <= 100) {
    Console.WriteLine(parsedValue);
}
于 2019-12-07T18:13:15.970 回答