我的代码输出重复
My code output repeats
我正在为直角三角形的三角形查找参数执行此代码但输出似乎是正确的,但重复
#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 == 3
和b == 4
,那么内循环中也会有a == 4
和b == 3
。
输出的主要测试是以下
intiger = sqrt((b*b)+(a*a));
c = sqrt((b*b)+(a*a));
if(c == intiger)
{
如果此测试适用于a
和b
,那么当数字对反转时,它将起作用(如果它适用于3,4,那么它将适用于4,3。
稍后,您将对结果输出进行排序
sort(array, array +3);
这导致不同的有序对在数组中具有相同的顺序。输出这个最终值,看起来相同的值显示了两次。
要修复此问题,请执行以下之一
- 不对数组进行排序
- 更改循环,这样就不会同时得到两对值
正如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;
}
相关文章:
- 为什么我的代码在输出中增加了93天
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 在我的代码中,获得最大的Pair Wise产品C++和输出并不总是正确的
- 我无法获取以下代码的输出
- 为什么我的C++程序的程序集输出充满了 .ascii,没有汇编代码?
- 编译并运行后,输出未出现在 Visual Studio 代码中
- VI工作室代码错误无法打开输出文件主.exe
- 代码编译没有任何输出,入门程序
- 与其他编译器相比,相同的代码在工作室Microsoft提供不同的输出
- 可能我知道为什么这段代码没有给出任何输出吗?
- 从排序数组中删除重复项,具有不同代码方式的相同解决方案具有不同的输出
- Clang 给了我符号更改的警告,但代码仍然产生正确的输出
- 为什么这两个版本的代码给出不同的输出
- 以下与指针相关的代码的输出是什么?
- C++和 Python 中的代码相同,但输出不同
- 为什么我的代码块上没有显示输出?
- C++ 高级代码未给出正确的输出
- (C++)分解这个简单的输入/输出代码:
- 错误的输出代码
- 奇怪的输出(代码块codebblocks -16.01mingw-setup.exe)