检查 a,b ,c边的直角是否有效,但您不能使用循环、条件、数组或更高级的功能



我有整数a,b和c。

有效的直角意味着所有边都是正整数,并且它们构成有效的直角三角形。

然后我必须输出结果(简单(。

完整免责声明:这是我正在尝试完成的课程和作业

我的尝试(Java(:

// int a, b, c = 3, 4, 5;
// how do I even start checking if I'm not allowed to use "if / else"
// therefore not shown in code
int aSquare = a * a;
int bSquare = b * b;
int cSquare = c * c;
// *Im hoping they dont flag this as a conditional
System.out.println(
(aSquare == (bSquare + cSquare) || bSquare == (cSquare + aSquare)
|| cSquare == (aSquare + bSquare))
);

最小边是abc的最小值;最大的边是abc的最大值;另一边是ab之和,c减去最小边和最大边。然后,我们需要做的就是检查最小边是否大于 0,最小边的平方加上中间边的平方等于最大边的平方。

final int smallest = Math.min(a, Math.min(b, c));
final int largest = Math.max(a, Math.max(b, c));
final int middle = a + b + c - smallest - largest;
System.out.println(smallest > 0 && smallest * smallest + middle * middle == largest * largest);

根据问题的性质,如果用户输入负数,使用assert更有意义:

assert a > 0 && b > 0 && c > 0: "Sides can not be negative";

此外,还可以使用按位运算符提取整数符号:

// sign is 1 if i is zero, 0 if it is negative, 2 if it is positive 
int sign = 1 + (i >> 31) - (-i >> 31); 

最新更新