我的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;
}
}
最佳答案
如果只是4
自然数,执行以下操作。
- 首先,创建一个普通数组(即
int[4]
或)std::array<int, 4>
并获得用户输入。 - 将数组升序(或降序)排序。
- (1st + 4th) 元素和 (2th + 3th 之间的区别) 元素 给出结果。
这是示例代码
#include <iostream>
#include <array> // std::array
#include <algorithm> // std::sort
int main()
{
std::array<int, 4> arr;
for (int& element : arr) std::cin >> element;
std::sort(arr.begin(), arr.end());
int result = (arr[0] + arr[3]) - (arr[1] + arr[2]);
std::cout << "The smallest difference is: " << result << "\n";
}
( See live online )
关于c++ - 可以将 4 位数字成对求和的算法,以便它们的和差尽可能接近,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58052272/