如何从一组变量中找出最小值

时间:2018-09-19 02:39:48

标签: c++

基本上,我有一个掷骰子程序,掷4个骰子,然后为您提供输出。我想添加一个附加功能,以找到这些纸卷的最低价值,并将其他三个纸卷加在一起,输出结果。

这是当前程序

    #include <iostream>
    #include <iomanip>
    #include <Windows.h>
    #include <ctime>
    #include <cstdlib>

    using namespace std;

    int main()
    {
                int d61;
                srand(time(NULL));
                d61 = rand() % 6 + 1;

                Sleep(1000);

                int d62;
                srand(time(NULL));
                d62 = rand() % 6 + 1;

                Sleep(1000);

                int d63;
                srand(time(NULL));
                d63 = rand() % 6 + 1;

                Sleep(1000);

                int d64;
                srand(time(NULL));
                d64 = rand() % 6 + 1;
                cout << endl << "You rolled a " << d61 << ", " << d62 << ", " << d63 << ", and a " << d64 << "." << endl;
                //Find lowest number
                //Add other three numbers together, make that a variable called 'roll'
                //cout << "The highest 3 rolls added together are " << roll << "." << endl;
    }

任何人和所有帮助将不胜感激!

2 个答案:

答案 0 :(得分:3)

std::min可以列出一个初始化列表,因此您可以一次比较它们。

auto minimum = std::min({d61, d62, d63, d64});

,您可以通过一些数学运算找到其他三个的和(不是最小的和):

auto sum_of_three = d61 + d62 + d63 + d64 - minimum;

答案 1 :(得分:1)

您只需将它们全部进行比较:

int dmin = d61;
if (d62 < dmin) dmin = d62;
if (d63 < dmin) dmin = d63;
if (d64 < dmin) dmin = d64;
cout << "The minimum is " << dmin << endl;