C# 程序要求输入一个整数,然后返回相同的数字
在C#中,如果我输入20,它将返回50,但在声明的int应该更改的位置没有数学方程。我想知道我做错了什么。这是代码C# 程序要求输入一个整数,然后返回相同的数字,c#,C#,在C#中,如果我输入20,它将返回50,但在声明的int应该更改的位置没有数学方程。我想知道我做错了什么。这是代码 namespace Lab1 { class Turtle { private int weight; public int Weight { get { return weight; } set { weight = value; } }
namespace Lab1
{
class Turtle
{
private int weight;
public int Weight
{
get { return weight; }
set { weight = value; }
}
public int getWeight()
{
return weight;
}
public Turtle(int wgt)
{
weight = wgt;
}
public void PrintVitals()
{
Console.WriteLine("Weight: {0}", weight);
}
static void Main(string[] args)
{
Console.WriteLine("Please Enter the Turtle's Weight: ");
int wgt = Console.Read();
Turtle turt = new Turtle(wgt);
Console.Write(turt.getWeight());
Console.WriteLine("\nPres Any Key To End");
Console.ReadKey();
}
}
}
编辑:
很抱歉,根据MSDN,Console.Read()返回一个int,即
输入流中的下一个字符,如果当前没有更多字符可读取,则为负字符(-1)
请尝试
Console.ReadLine()
Console.Read返回一个整数,表示按下字符的ascii码。但是,20是有效的ascii。ascii中的2是50。因为您使用的是Read而不是ReadLine,所以无论是否按“下一步”0,当您按2时都会执行Read。它将2的ascii转换为整数,因此“2”变为50
要解决此问题,请通过将console.ReadLine解析为整数
string input = Console.ReadLine();
int wgt = int.Parse(input);
将主方法更改为:
static void Main(string[] args)
{
int wgt = 0;
Console.WriteLine("Please Enter the Turtle's Weight: ");
string line = Console.ReadLine();
if (int.TryParse(line, out wgt)) {
Turtle turt = new Turtle(wgt);
Console.Write(turt.getWeight());
} else {
Console.WriteLine("You must enter an integer.");
}
Console.WriteLine("\nPres Any Key To End");
Console.ReadKey();
}
您试图将字符串(控制台输入)读取为int。上面的方法将通过解析将字符串正确转换为int。注意
TryParse()方法中的“out”关键字。更改第15行和第16行
string wgt = Console.ReadLine();
Turtle turt = new Turtle(int.Parse(wgt));
Console.Read不会返回您认为它会返回的内容。您是否使用调试器逐步完成了程序?这几乎可以确定预期行为与实际行为的偏差。如果你逐行检查每个函数的结果,你会很快发现问题。在找出调试器的问题所在后,更好的问题可能是“当我在控制台中键入“20”时,Console.Read()为什么会返回50的值?”嗯,如果您检查它,以便确定不猜测,会怎么样?无论哪种方式,他都需要检查该输入,并在执行时检查该输入。