2012-03-11 51 views
1

我做的三角形找到perameters此代碼爲直角三角形 但輸出似乎出來的權利,但反覆我的代碼輸出重複

#include<iostream> 
#include<vector> 
#include<list> 
#include <math.h> 
#include <algorithm> 


using namespace std; 

int main() 
{ 
    int a; 
    float c; 
    vector<double> retval; 
    double intiger; 
    double p; 
    double l = 25; 
    float array[3]; 

    for (int b=1; b < l; b++) { 
     for (int a=1; a < l; a++) { 
      intiger = sqrt((b*b)+(a*a)); 
      c = sqrt((b*b)+(a*a)); 
      if (c == intiger) { 
       array[0]=a; 
       array[1]=b; 
       array[2]=c; 
       //int elements = sizeof(array); 
       //cout << elements << endl; 
       sort(array, array +3); 
       //retval.push_back(a); 
       //retval.push_back(b); 
       //retval.push_back(c); 
       if (c == a) { 
        continue; 
       } 
       p = a + b + c; 
       if (p > l) { 
        break; 
       } 
       //cout << "p == " << p << endl; 
      } else { 
       continue; 
      } 

      //if (retval.size()== 62) 
      //cout << c <<endl; 
      //cout << " a = " << a << " b = " << b << " c = " << c << " " 
      cout << array[0] << " " << array[1] << " " << array[2] << endl; 
     } 
    } 

    return 0; 
} 

輸出出來要重複兩次。

3 4 5 

3 4 5 

6 8 10 

6 8 10 

我想讓它重複一次。

+3

請您縮進碼。 – 2012-03-11 02:48:05

+0

將「cout」向下移動1行,在}之後。 – TreyA 2012-03-11 02:48:16

+0

我移動了cout,但代碼出來了,但它仍然重複 – user1261771 2012-03-11 02:54:57

回答

3

這個重複的原因與算法中的排序有關。嵌套循環確保您將在兩個訂單中獲得每個數字對。示例如果您在內部循環中有a == 3b == 4,那麼您在內部循環中也將有a == 4b == 3

輸出主要測試的是以下

intiger = sqrt((b*b)+(a*a)); 
c = sqrt((b*b)+(a*a)); 
if(c == intiger) 
{ 

如果該測試適用於ab然後它會工作時的數字對被逆轉(如果它工作3,4,然後它會爲工作4,3

後來你排序結果輸出

sort(array, array +3); 

這將導致不同的有序對具有相同或在數組中。輸出這個最終值,看起來像相同的值顯示兩次。

爲了解決這個問題做了以下

  1. 一個不排序的數組
  2. 更改循環,使你沒有得到這兩個值對。
0

由於JaredPar說不要讓a,b得到相同的值對。像(3,4)和(4,3)一樣。如果按照排序順序排列,則兩者都會給出與(3,4,5)相同的結果。

對於改變for循環....

for (int b=1; b < l; b++) 
     for (int a=1; a < b; a++) 

而且,您可以修改代碼的continue和break語句來提高reability像如下....

#include<iostream> 
#include<vector> 
#include<list> 
#include <math.h> 
#include <algorithm> 


using namespace std; 

int main() 
{ 
    int a; 
    float c; 
    vector<double> retval; 
    double integer; 

    double l = 25; 
    float array[3]; 

     for (int b=1; b < l; b++) 
      for (int a=1; a < b; a++) { 

      integer = sqrt((b*b)+(a*a)); 
      c = sqrt((b*b)+(a*a)); 

      if (c != integer) 
      continue; 


      array[0]=a; 
      array[1]=b; 
      array[2]=c; 
      sort(array, array +3); 

      if(c != a && a+b+c > l) 
      break; 

      cout << array[0] << " " << array[1] << " " << array[2] << endl; 

      } 


     return 0; 
    }