【发布时间】:2019-09-22 18:29:52
【问题描述】:
我在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 我添加了代码。它不完整,但我希望你能明白。 0 来自将这 4 个数字成对相加:4+1 = 5 和 3 + 2 = 5,它们的差为 0
标签: c++ algorithm if-statement simplify