【发布时间】:2014-04-04 11:29:28
【问题描述】:
在做一些 C# 练习时遇到了这个问题。
// 仅使用 5 if 语句查找五个数字中最大的一个。
我不知道怎么做,所以我在网上查了一下,我设置了这个。
Console.Write("Type number 1:"); double a = double.Parse(Console.ReadLine());
Console.Write("Type number 2:"); double b = double.Parse(Console.ReadLine());
Console.Write("Type number 3:"); double c = double.Parse(Console.ReadLine());
Console.Write("Type number 4:"); double d = double.Parse(Console.ReadLine());
Console.Write("Type number 5:"); double e = double.Parse(Console.ReadLine());
double max;
if (a > b && a > c && a > d && a > e)
{
max = a;
Console.WriteLine("The biggest number from {0} , {1} and {2} is {3}.", a, b, c, max);
}
else if (b > a && b > c && b > d && b > e)
{
max = b;
Console.WriteLine("The biggest number from {0} , {1} and {2} is {3}.", a, b, c, max);
}
else if (c > a && c > b && c > d && c > e)
{
max = c;
Console.WriteLine("The biggest number from {0} , {1} and {2} is {3}.", a, b, c, max);
}
else if (d > a && d > b && d > c && d > e)
{
max = d;
Console.WriteLine("The biggest number from {0} , {1} and {2} is {3}.", a, b, c, max);
}
else
{
max = e;
Console.WriteLine("The biggest number from {0} , {1} and {2} is {3}.", a, b, c, max);
}
使用练习示例,它会返回正确的数据。例如
5 2 2 4 1 return: 5
但经过进一步测试后,我发现这是错误的:
-1 -2 -2 -1 -15 return: -15
要么我一年级的数学技能有误,要么 -15 不大于 -1。我知道错误在哪里,但我不知道如何真正解决它。
【问题讨论】:
-
我认为你应该使用
>=而不是>。否则你有false-1 > -1 -
而且你总是在你的
Console.WriteLine中使用a, b, c, max。是否有任何特殊原因将您的string解析为double而不是int? -
是的,这似乎有效。我会做更多的测试。
-
如果您已完成学业,请使用
double max = new[] { a, b, c, d, e }.Max();。
标签: c# if-statement compare