c# - If 和 Else if block 仅运行 Else if

标签 c# if-statement

这整个简单的代码似乎是正确的,但是当我单击开始并输入任何数字(例如 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/

相关文章:

java - 如何使用instanceof关键字Java

perl - Perl 中针对多个模式的字符串匹配

c# - 在命令中移动滚动条

c# - 过滤后如何将位置应用于节点

c# - 在 .ashx 页面中使用文件的相对路径

c# - Y/N 或循环中的 y/n

与 if 语句中的字符串比较不起作用

用于可移植跨平台的 c# .NET 4.5 HttpWebRequest

c# - 使用 .net 库以编程方式创建 SAML 协议(protocol)登录请求

java - 声明数组长度,JAVA