我是Console Application的新手,我通常使用C#代替Unity。代码实际上并不像我想要的那样
是的我知道使用Goto并不好。但我不知道替代品
我有[a = 2] [b = 3]和[ans = a + b],所以显而易见的答案是5.所以当你输入5时,它会运行Else语句,这使得它不正确。
goto start;
error:
Console.Clear();
Console.WriteLine("Input not Recognized");
Console.WriteLine("Try Again");
Console.WriteLine("\nType (Reset) to Reset Program");
Console.WriteLine("\nType (End) to End Program");
Console.WriteLine("");
string error1 = Console.ReadLine();
if (error1.Equals("reset", StringComparison.InvariantCultureIgnoreCase))
{
goto start;
}
if (error1.Equals("end", StringComparison.InvariantCultureIgnoreCase))
{
Environment.Exit(0);
}
else
{
goto error;
}
start:
Console.WriteLine("Solve the Math Equation");
int a = 2;
int b = 3;
int ans = a + b;
Console.WriteLine("\n2 + 3");
Console.WriteLine("");
string user = "";
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace)
{
double val = 0;
bool _x = double.TryParse(key.KeyChar.ToString(), out val);
if (_x)
{
user += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (key.Key == ConsoleKey.Backspace && user.Length > 0)
{
user = user.Substring(0, (user.Length - 1));
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
if (user.Equals(ans))
{
Console.Clear();
Console.WriteLine("Correct!");
Console.WriteLine("\nYour answer " + ans);
Console.WriteLine("\nType (End) to End Program");
Console.WriteLine("");
string end1 = Console.ReadLine();
if (end1.Equals("end", StringComparison.InvariantCultureIgnoreCase))
{
Environment.Exit(0);
}
else
{
goto error;
}
}
else
{
Console.Clear();
Console.WriteLine("Incorrect!");
Console.WriteLine("\nThe answer was " + ans);
Console.WriteLine("\nType (Reset) to Reset Program");
Console.WriteLine("Type (End) to End Program");
Console.WriteLine("");
string rne1 = Console.ReadLine();
if (rne1.Equals("reset", StringComparison.InvariantCultureIgnoreCase))
{
Console.Clear();
goto start;
}
if (rne1.Equals("end", StringComparison.InvariantCultureIgnoreCase))
{
Environment.Exit(0);
}
else
goto error;
答案 0 :(得分:1)
您的user
和ans
在您的代码中不相同,这就是您的代码跳转到错误的原因。他们不平等的原因是他们的类型。
user
是一个字符串
ans
是一个整数
所以你要比较" 5"到5并且不能相等。
转换其中一个变量,使您具有相同的类型。
在if语句中使用user.Equals(ans.ToString())
或将字符串转换为数字(这是更好的解决方案IMO - 因为它还处理输入不是数字时的情况)。像这样:
int userAns;
if (!Int32.TryParse(user, userAnsj))
Console.WriteLine("Input is not a valid integer.");
然后comapare userAns
到ans
。