2014-10-09 43 views
0

我的程序应该列出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; 
} 
+1

循环过多:如果您知道'a'和'b',则可以计算'c'。 – 2014-10-09 03:23:46

回答

1

下面的行不会做你所期望的:

// 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:由于@代码学徒进一步评论,a <= 500 && b <= 500已经由for -loop保证,因此可以简化为:

if ((a*a)+(b*b) == c*c) { 
+1

请注意,“a <= 500”和“b <= 500”的条件是冗余的,因为这由for循环计数器保证。 – 2014-10-09 03:11:32

+0

@ Code-Apprentice编辑,thx。 – herohuyongtao 2014-10-09 03:14:33

0

你很可能会计算一些三元组的两倍。如果你检查你的输出,你一定会看到“3,4,5”重复6次。实际上,三倍会重复6次。这表明,速战速决是6

或者划分你的柜台,就可以确保你没有使用外环定义为内部循环的起点重复任何三元:

for (int a = 1; a <= 500; a++) 
{ 
    // Makes sure side B starts at 1 and is less than 500 
    for (int b = a + 1; b <= 500; b++) 
    { 
     // Makes sure side C starts at 1 and us kess than 500 
     for (int c = b + 1; c <= 500; c++) 

ps此外,您的if条件中的错误保证数字的组合被计数,因此输出是625000000。请务必按照herohuyongtao's answer中所述修复此问题。

+0

好...但是不需要循环来查找'c',只需使用sqrt。 – 2014-10-09 03:22:36

+0

@BenVoigt一旦OP得到一个正确的解决方案,这当然是一个体面的优化。 – 2014-10-09 03:27:11

1

强制三元组在创建之前进行排序。斜边将永远是最后的,最短的腿永远是第一。 (我们不需要担心(a,a,b),因为这样的整数组合不会存在。

因此对于解决方案triple(a,b,c),应该总是如此,< b < C,且a> 0,b> 0,C> 0

容易。:)

0

计数器并不初始化为0哪里是你的逻辑跳跃如三角形?