我必须写一个代码,将要求3个整数值,并找到最大的一个。 但是,如果用户输入非数字值,则该值必须为零。 到目前为止我写了这个
int a, b, c;
Console.WriteLine("Enter value 1:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value 2:");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value 3:");
c = Convert.ToInt32(Console.ReadLine());
if (a > b && a > c)
{
Console.WriteLine("The greatest value is: {0}", a);
}
if (b > a && b > c)
{
Console.WriteLine("The greatest value is: {0}", b);
}
if (c > a && c > b)
{
Console.WriteLine("The greatest value is: {0}", c);
}
此代码只对数字起作用。 我的问题是,我不能使非数字输入的值为零。 我尝试使用string而不是int,所以没有错误,但是我不能使用“>” 在if语句中使用字符串,我还尝试使用作为默认值,因为when是默认值,所以它是零。
谢谢
您只需替换:
x = Convert.ToInt32(Console.ReadLine());
用。。。
int.TryParse(Console.ReadLine(), out int x);
如果无法解析输入,x
将以0结束。