我有一份 C++
作业,需要我输入 4
个自然数,并将它们配对,使它们的和之间的差异尽可能地小。
例如:
I have entered 4 numbers: 4; 3; 2; 1;
The smallest between the numbers would be 0 --> 4 + 1 and 3 + 2
我已经写了一些使用if语句的代码,但检查每种组合需要编写大量的代码,所以我想知道是否有更短的方法来完成这个任务。
#include <iostream>
using namespace std;
int main()
{
int a, b, c, d;
int x, y, z;
cout << "Insert 1st number" << endl;
cin >> a;
cout << "Insert 2nd number" << endl;
cin >> b;
cout << "Insert 3rd number" << endl;
cin >> c;
cout << "Insert 4th number" << endl;
cin >> d;
if ((a > b) && (b > c) && (c > d))
{
x = a + d;
y = b + c;
z = x - y;
cout << "The smallest differnce is: " << z << endl;
cout << endl;
}
else if ((a > b) && (b > c) && (c < d))
{
x = a + c;
y = b + d;
z = x - y;
cout << "The smallest differnce is: " << z << endl;
cout << endl;
}
else if ((a > b) && (b < c) && (c > d))
{
x = a + b;
y = d + c;
z = x - y;
cout << "The smallest differnce is: " << z << endl;
cout << endl;
}
}
0
是从哪里来的? - PhoenixBlue