求所有和中最大的和,它包含数字和

Find the biggest sum out of the all, it containing numbers and

本文关键字:包含 数字      更新时间:2023-10-16

我需要找到最大和,它包含数字和两个数字中的第一个还是第二个更大如何找到它?

假设n=10,两个put数分别为6和2,分别为:7和1,5和6,1和8,4和3。那么答案应该是,最大的和是11,它包含的数字是5和6,更大的麻木是第二个。

我有一个代码:

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{

int p, a, i;
int n;
int sum;
ofstream fr("Rezults.txt");
ifstream fd("Data.txt");
fd>>n;
cout<<n<<endl;


for (i=1; i<=n/2; i++)
{
    fd>>p>>a;
    sum=p+a;
    for (int j=sum; j<=n/2; j++);
    {
            cout<<sum<<endl;
    }
}

fd.close();
fr<<sum;
fr.close();

return 0;
}

我认为您的代码应该是这样的:

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{

int p, a, i;
int n;
int sum;
ofstream fr("Rezults.txt");
ifstream fd("Data.txt");
fd>>n;
cout<<n<<endl;

fd>>p>>a;
int biggestSum=p+a;
int first = p;
int second = a;
for (i=2; i<=n/2; i++)
{
    fd>>p>>a;
    sum=p+a;
    if(sum > biggestSum)
    {
        biggestSum = sum;
        first = p;
        second = a;
    }
}
cout <<"biggest sum is "<<biggestSum<<"n";
cout <<"The first number is "<<first<<"n";
cout<<"The second number is "<<second<<"n";
fd.close();
fr<<sum;
fr.close();

return 0;
}

updated:您应该小心for循环的索引i,它应该以2开头,因为您在for循环之前读取了前两个数字。