[英]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.Parse或int.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.