这整个简单的代码似乎是正确的,但是当我单击开始并输入任何数字(例如 4 或 6)时,每次唯一的输出是“else if”!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
int c = Convert.ToInt32(Console.Read());
if (c >= 0 && c < 5)
{
Console.Write("# is > 0");
}
else if (c >= 5)
{
Console.Write("# is > 5");
}
Console.ReadKey();
}
}
}
最佳答案
Console.Read
阅读:
The next character from the input stream, [...]
如果您查看 ASCII table ,您会注意到代表数字的字符的值从 48 开始。您获得的值已经是一个整数,因此无需转换(请参阅文档中的 Console.Read
签名)。根据 Travis J 的建议,您可以使用以下代码,以获得预期的结果:
int c = Convert.ToInt32(Console.ReadLine());
正如您在 the documentation for Console.ReadLine
中看到的那样- 它返回一个字符串
。
考虑使用调试器,如您问题下的评论中所建议的,同时阅读文档。
关于c# - If 和 Else if block 仅运行 Else if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32791398/