[英]C# How set a non-numeric value to 0
我必须编写一个代码来要求 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);
}
此代码仅适用于数字。 我的问题是我不能让非数字输入的值为零。 我尝试使用字符串而不是 int,所以没有错误,但我不能在 if 语句中使用 ">" 字符串,我也尝试使用默认值,因为默认值是什么,所以它为零。
谢谢
你可以替换:
x = Convert.ToInt32(Console.ReadLine());
和...
int.TryParse(Console.ReadLine(), out int x);
如果无法解析输入,则x
最终将为 0。
我认为您可以创建一个执行 try catch 的 function,这样您就可以打印一条消息,说明输入不是数字。
static int Check(string input)
{
int result;
try
{
result = Convert.ToInt32(input);
}
catch (FormatException e)
{
Console.WriteLine("Input not integer, the value assigned is 0");
result = 0;
}
return result;
}
为了实现你只需调用:
a = Check(Console.ReadLine());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.