C ++的三个整数的升序

时间:2017-07-07 09:58:38

标签: c++

#include <iostream>

using namespace std;

int main()
{
    int a;
    int b;
    int c;

    cout << "Please input three integers:" << endl;
    cout << ">> ";
    cin >> a >> b >> c;
    cout << endl;

    if (((a == a) && (b > a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << c << " " << b;
    }
    else if (((a == a) && (b >= a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << b << " " << c;
    }
    else if (((a > b) && (b == b)) && (c >= b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " << a;
    }
    else if (((a >= b) && (b == b)) && (c < b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << a << " " << b;
    }
    else if (((a > c) && (b >= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << b << " " << a;
    }
    else if (((a >= c) && (b <= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " << a;
    }

    return 0;
}

对于此分配,我使用1,2和3输入整数。 我的问题是为什么这些输入(1,2,3)和(2,1,3)和(3,2,1) 不升级吗?

3 个答案:

答案 0 :(得分:2)

您拥有正确数量的案例(6种可能的排序)但条件错误。我只会通过第一个......

if (((a == a) && (b > a)) && (c >= a)) {
        cout << a << " " << c << " " << b;
}

传递条件的输入是a=1b=2c=3,但1 3 2不是正确的顺序。要确保a c b正在提升,您需要

if (( c >= a) && (b >= c)) 

(这里你不需要第三个,因为通过传递性,如果c>=ab>=c,那么b>=a也成立。

答案 1 :(得分:1)

如果我正确理解了您的问题,您也可以使用std::sort标题中的algorithm

int vals[] { 3, 1, 2 };
std::sort(vals, vals + 3);
cout << vals[0] << vals[1] << vals[2]; // prints 123

答案 2 :(得分:0)

你真的想确保输入的数字在升序中。单个测试可以确保这一点。

  do 
    {
        cout << "Enter 3 numbers in ascending order: ";
        cin >> arr[0] >> arr[1] >> arr[2];
    }while(!(arr[0] <= arr[1] && arr[1] <= arr[2]));