我需要找到最大金额和它包含数字和两个中的第一个或第二个数字是否更大 。如何找到它?
假设n = 10,两个数字是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;
}
答案 0 :(得分:1)
我认为你的代码应该是这样的:
#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;
}
更新:你应该注意for循环的索引i它应该从2开始,因为你在for循环之前读了前两个数字。