c++ - 可以将 4 位数字成对求和的算法,以便它们的和差尽可能接近

标签 c++ algorithm if-statement simplify

我的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/

相关文章:

python - 如何将 Firebase 与基于 Linux 的客户端应用程序一起使用,以便与服务器进行双向消息通信

java - 大型数组的快速排序 stackoverflow 错误

javascript - 在这种特定情况下,if-else 是否比 try-catch 更好,性能明智?哪种方式是最佳做法?

c++ - 如何在该程序中将if else语句转换为switch语句? Visual Studio 2019 C++

c++ - 检测一个类型是来自主模板的特化还是用户提供的特化

c++ - boost 图 : dijkstra_shortest_paths: cannot form a reference to 'void'

C++ 预编译头文件和包含文件组织

java - 步数最少的寻路算法

python - 编写算法以在给定范围内用 Python 生成素数

c++ - !(variable) 和 (!variable) 之间的区别