问题描述
我目前正在尝试这个问题:
I am currently attempting this question :
例如,3 + 4 = 9 + 16 = 25 = 5 。
For example, 3 + 4 = 9 + 16 = 25 = 5.
恰好有一个毕达哥拉斯三元组,其中a + b + c = 1000.
查找产品abc。
There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
我的代码如下,我认为它应该是正确的,但该网站告诉我我的答案是错的?有人可以帮我看看我的逻辑中的缺陷吗?
My code is as follows, I think it should be correct, but the site is telling me my answer is wrong? Can someone help me see the flaws in my logic please?
public class Pythagoras {
public static void main(String[] args) {
int sum = 1000;
int a;
int product=0;
for (a = 1; a <= sum/3; a++)
{
int b;
for (b = a + 1; b <= sum/2; b++)
{
int c = sum - a - b;
if ( c > 0 && (a*a + b*b == c*c) )
System.out.printf("a=%d, b=%d, c=%d\n",a,b,c);
product = a * b * c;
}
}
System.out.println(product);
}
}
推荐答案
我以为你错过了一套大括号。缩进使我相信两个最内层的陈述在一起,但你需要花括号才能正确。
I think you're missing a set of braces. The indentation leads me to believe the two innermost statements go together but you need curly braces for that to be correct.
if ( c > 0 && (a*a + b*b == c*c) )
{
System.out.printf("a=%d, b=%d, c=%d\n",a,b,c);
product = a * b * c;
}
没有大括号产品
将始终包含最后值 a
, b
的产品,以及 C
。 (333 * 500 * 167 == 27805500)。
Without the braces product
will always contain the product of the last values of a
, b
, and c
. (333 * 500 * 167 == 27805500).
这篇关于寻找毕达哥拉斯三胞胎的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!