在C#中,如果我输入20,则返回50但是没有数学等式,其中声明的int应该被更改。我想知道我做错了什么。这是代码。
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();
}
}
}
答案 0 :(得分:2)
Console.Read返回一个整数,表示按下的字符的ascii。但是,20是有效的ascii。 ascii中的2是50.因为您正在使用Read而不是ReadLine读取时按下2执行无论您是否按下0。它将ascii为2转换为整数,因此" 2"变成50岁。
要解决此问题,请将console.ReadLine解析为整数,
string input = Console.ReadLine();
int wgt = int.Parse(input);
答案 1 :(得分:0)
编辑:
抱歉,根据MSDN,Console.Read()返回一个int,即
输入流中的下一个字符,如果当前没有更多字符要读取,则为负一(-1)。
尝试Console.ReadLine()
答案 2 :(得分:0)
将主要方法更改为:
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。请注意" out" TryParse()
方法中的关键字。
答案 3 :(得分:0)
更改第15行和第16行。
string wgt = Console.ReadLine();
Turtle turt = new Turtle(int.Parse(wgt));