我被要求(上学)编写一个无效的函数并输出用户输入的三角形类型:
static void typeTri()
{
if (side1 == side2 && side2 == side3)
{
Console.WriteLine("The triangle is equilateral.");
}
else if ((side1 == side2 && side2 != side3) || (side1 != side2 && side2 == side3) || (side1 == side3 && side1 != side2))
{
Console.WriteLine("The triangle is isoceles.");
}
else
{
Console.WriteLine("The triangle is scalene.");
}
}
对'else if'的测试似乎有点长。有什么想法吗?
答案 0 :(得分:7)
多亏了逻辑,你可以简化第二个if
:你不需要测试!=
,因为如果它们相等,那么第一个if
就已经满足了。
static void typeTri()
{
if (side1 == side2 && side2 == side3)
{
Console.WriteLine("The triangle is equilateral.");
}
else if ((side1 == side2) || (side2 == side3) || (side1 == side3))
{
Console.WriteLine("The triangle is isoceles.");
}
else if ((side1 >= side2 + side3) || (side2 >= side1 + side3) || (side3 >= side1 + side2) || (side1 <= 0) || (side2 <= 0) || (side3 <= 0))
{
Console.WriteLine("Not a Triangle");
}
else
{
Console.WriteLine("The triangle is scalene.");
}
}
您还需要考虑这不是三角形的情况,但该要求可能超出了这个特定问题的范围。
答案 1 :(得分:4)
按您说话的方式对其进行编码......
如果所有方面都相同,则三角形是等边的&#39;否则,如果至少两边是相等的,则三角形是Isosceles&#39;否则,&#39;三角形是scalene&#39;
下面写的typeTri()
方法可以像上面的句子一样说。
static void typeTri()
{
if (AllSidesAreEqual(side1, side2, side3))
{
Console.WriteLine("The triangle is equilateral.");
}
else if (AtLeastTwoSideAreEqual(side1, side2, side3))
{
Console.WriteLine("The triangle is isoceles.");
}
else
{
Console.WriteLine("The triangle is scalene.");
}
}
private static bool AllSidesAreEqual (int side1, int side2, int side3)
{
return (side1 == side2)
&& (side2 == side3);
}
private static bool AtLeastTwoSideAreEqual (int side1, int side2, int side3)
{
return (side1 == side2)
|| (side2 == side3)
|| (side1 == side3);
}
答案 2 :(得分:0)
这最大限度地减少了条件,并且通过使用三元运算符,它是紧凑的:
Console.WriteLine(
"The triangle is {0}.",
side1 != side2
? (side2 != side3 && side1 != side3 ? "scalene" : "isoceles")
: (side3 == side1 ? "equilateral" : "iscoceles");
答案 3 :(得分:0)
这个版本将条件检查减少到3,代价是一些数学欺骗:
int count = 0;
if (side1 - side2 != 0) count++;
if (side2 - side3 != 0) count++;
if (side3 - side1 != 0) count++;
var types = new [] { "equilateral", "invalid", "isoceles", "scalene" };
Console.WriteLine("The triangle is {0}.", types[count]);
比较减少了长度与任何双方长度差异比较的比较。然后查找表。