C# 有人能解释为什么转换为int并使用read line而不是read修复了我的问题吗?
所以之前我在寻找随机生成的数字和用户输入之间的差异时遇到了很多麻烦。我做了一些搜索,发现我无法使用C# 有人能解释为什么转换为int并使用read line而不是read修复了我的问题吗?,c#,C#,所以之前我在寻找随机生成的数字和用户输入之间的差异时遇到了很多麻烦。我做了一些搜索,发现我无法使用Console.Read()
Console.Read()实际上我必须使用这个intguess=Convert.ToInt32(Console.ReadLine())代码>在玩它时,我意外地使它转换为.ToInt32(Console.Read())这反过来又使数学完全错误了。道歉如果我没有有效地解释我自己,我是新的编码,这是为了学习的东西。谢谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Would you like to play the guessing game?");
string input = Console.ReadLine();
if (input.Equals("yes"))
{
Console.WriteLine("Alright! The rules are simple, i'll think of a number and you guess it!");
Console.WriteLine("Alright enter your guess: ");
int guess = Convert.ToInt32(Console.ReadLine());
Random rand = new Random();
int answer = rand.Next(1,11);
if (rand.Equals(guess))
{
Console.WriteLine("Congratulations you guessed correctly!");
}
else
{
Console.WriteLine("Aww you were so close! I guessed " + answer);
int difference = guess - answer;
Console.WriteLine("you were only " + Math.Abs(difference) + " away");
}
} else
{
Console.WriteLine("Closing application...");
Thread.Sleep(1000);
Environment.Exit(0);
}
}
}
}
Console.Read()将只获取一个字符和控制台。ReadLine()获取整行或用户键入的所有内容,直到它发现按下了“Enter”键。Console.Read()将仅获取一个字符和控制台。ReadLine()获取整行或用户键入的所有内容,直到它发现按下了“Enter”键
Console.Read()
返回正在输入的单个字符的ascii值
例如,输入“A”将返回65
。有关ascii代码的列表,请参阅。请注意,1
的ascii值实际上是49
Convert.ToInt32(Console.ReadLine());
读取整行并尝试将其转换为整数
返回正在输入的单个字符的ascii值
例如,输入“A”将返回65
。有关ascii代码的列表,请参阅。请注意,1
的ascii值实际上是49
Convert.ToInt32(Console.ReadLine());
读取整行并尝试将其转换为整数 因为控制台。读取从控制台读取字符。它以整数形式返回。因此,当您输入“是”时,输出将为
121 = y
101 = e
115 = s
13 =
10 =
最后两个字符(13和10)等于Windows换行符。因为控制台。Read
从控制台读入字符。它以整数形式返回。因此,当您输入“是”时,输出将为
121 = y
101 = e
115 = s
13 =
10 =
最后两个字符(13和10)等于Windows换行符。Sweet,我甚至没有考虑ASCII值。谢天谢地,我知道你在说什么,哈哈。亲爱的,我甚至没有想到ASCII值。谢天谢地,我知道你在说什么,哈哈。