繁体   English   中英

C#Noob寻找小帮助:为什么这个迷你代码不起作用?

[英]C# Noob Looking for Little Help : Why this mini code doesnt works?

我是C#的新手,我只是在这里尝试一些代码。

但这没有用。 我不明白为什么。 而且我在Visual Studio上没有任何错误。 只是行不通。 我一直说:“您写的数字更大。”然后关闭。

你能帮助我吗?

您可以了解我正在尝试做的事情。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 4 ;

            Console.WriteLine("Hello");
            Console.WriteLine("Write a number from 1 to 10 : ");

            int x = Console.Read();

            if ( x < number )
                Console.WriteLine("You write a lower number.");
            else if ( x > number )
                Console.WriteLine("You write a higher number.");
            else
                Console.WriteLine("True");

            Console.Read();
        }
    }
}

只读读取下一个字符。

您要使用Console.ReadLine并使用int.Parseint.TryParse将字符串转换为整数。

int x = int.Parse(Console.ReadLine());

另外,我认为Read可以从数字0-9开始工作。 You write a higher number总是You write a higher number ,这是因为它正在比较字符值而不是数值,因为Read返回的是字符的十进制表示。

如果必须使用Read,则必须从字符值中获取数字值,如下所示:

int x = Console.Read();

int numericalX =  (int)char.GetNumericValue((char)x);

另外,就像其他人所建议的那样,我建议不使用int.TryParse而不是int.Parse ,给定的输入不是有效的整数值。 int.TryParse返回一个布尔值,该值指示转换是否成功,并将转换后的整数值作为out参数输出。

这是因为Console.Read()返回的是字符,而不是数字。 您可能需要一个ReadLine然后再调用int.TryParse

您应该做的第一件事是验证x值。 Console.Read()返回一个char值,该值可以隐式转换为int 因此,如果键入3,则x的值为51。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM