我的程序应该列出1-500之间的所有直角三角形三元组。它不应重复相同的三角形。例如3、4、5与4、3、5相同,只应显示第一个。我还应该在程序末尾有一个计数器,该计数器显示找到了多少个三角形。到目前为止,这就是我所拥有的。当前没有显示正确数量的三角形,并且计数器无法正常工作。谢谢
// Naming
int counter;
// For loops and nested for loops
{
// Makes sure side A starts at 1 and is less than 500
for (int a = 1; a <= 500; a++)
{
// Makes sure side B starts at 1 and is less than 500
for (int b = 1; b <= 500; b++)
{
// Makes sure side C starts at 1 and us kess than 500
for (int c = 1; c <= 500; c++)
{
// If A squared + B squared = C squared and C squared, A, and B -->
// are all less than or equal to 500 then display the answer
if ((a*a)+(b*b) == c*c & a & b <= 500) {
// This is my counter I cannot seem to get it to work properly
// More info about counter at bottom
counter++;
cout << a << ", " << b << ", " << c << endl;
}
}
}
}
}
cout << endl;
// Displaying counter
cout << counter << endl << endl ;
system("PAUSE");
return EXIT_SUCCESS;
}
最佳答案
以下行将无法满足您的期望:
// If A squared + B squared = C squared and C squared, A, and B -->
// are all less than or equal to 500 then display the answer
if ((a*a)+(b*b) == c*c & a & b <= 500) {
^^^^^^^^^^^^
更改为:
if ((a*a)+(b*b) == c*c && a <= 500 && b <= 500) {
ps:正如@ Code-Apprentice进一步说明的那样,
a <= 500 && b <= 500
循环已经保证了for
,因此可以将其简化为:if ((a*a)+(b*b) == c*c) {
关于c++ - 我的三角三元组程序有问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26269627/