我的代码输出重复

My code output repeats

本文关键字:输出 代码 我的      更新时间:2023-10-16

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

#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

我只想让它重复一次。

重复这种情况的原因与算法中的排序有关。嵌套循环确保您将获得两个顺序中的每个数字对。例如,如果内循环中有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. 更改循环,这样就不会同时得到两对值

正如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;
    }