2014-10-09 59 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哪裏是你的邏輯跳躍如三角形?