我的代码输出重复

时间:2012-03-11 02:44:58

标签: c++

我正在为直角三角形的三角形查找参数执行此代码 但输出结果似乎正确但重复

#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

我想让它重复一次。

2 个答案:

答案 0 :(得分: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. 更改循环,这样就不会获得两对值。

答案 1 :(得分: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语句以提高可恢复性,如下所示....

#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;
    }