21xrx.com
2024-12-22 22:04:32 Sunday
登录
文章检索 我的文章 写文章
C++:输入四个整数,按从小到大的顺序输出
2023-07-05 00:49:54 深夜i     --     --
C++ 输入 四个整数 从小到大 输出

C++编程是一种非常有趣的活动,它可以通过解决各种问题来增强我们的计算机技能和知识。在本文中,我们将看到如何使用C++编程输入四个整数,并按从小到大的顺序输出它们。

首先,我们使用C++的标准输入/输出库来获取四个整数。我们使用cin从用户输入读取四个整数,并使用cout将它们输出到屏幕上。例如:


int a, b, c, d;

cin >> a >> b >> c >> d;

cout << "You have entered: " << a << " " << b << " " << c << " " << d << endl;

接下来,我们将使用if语句来比较这四个整数,并按从小到大的顺序输出它们。我们使用if-else if语句来针对不同的情况进行操作。例如:


if (a <= b && a <= c && a <= d) {

  cout << a << " ";

  if (b <= c && b <= d) {

    cout << b << " ";

    if (c <= d)

      cout << c << " " << d << endl;

     else

      cout << d << " " << c << endl;

    

  } else if (c <= b && c <= d) {

    cout << c << " ";

    if (b <= d)

      cout << b << " " << d << endl;

     else

      cout << d << " " << b << endl;

    

  } else {

    cout << d << " ";

    if (b <= c)

      cout << b << " " << c << endl;

     else

      cout << c << " " << b << endl;

    

  }

} else if (b <= a && b <= c && b <= d)

  // Repeat the process for b as the smallest number.

else if (c <= a && c <= b && c <= d)

  // Repeat the process for c as the smallest number.

else

  // Repeat the process for d as the smallest number.

上面的代码使用嵌套if语句来比较四个数字,并确定它们之间的大小关系。它还使用cout来按从小到大的顺序输出这四个数字。

最后,我们可以将上述代码全部放在一起,并使用C++编译器进行编译和运行。以下是完整的程序:


#include <iostream>

using namespace std;

int main() {

  int a, b, c, d;

  cout << "Enter four integers: ";

  cin >> a >> b >> c >> d;

  cout << "You have entered: " << a << " " << b << " " << c << " " << d << endl;

  if (a <= b && a <= c && a <= d) {

    cout << a << " ";

    if (b <= c && b <= d) {

      cout << b << " ";

      if (c <= d)

        cout << c << " " << d << endl;

       else

        cout << d << " " << c << endl;

      

    } else if (c <= b && c <= d) {

      cout << c << " ";

      if (b <= d)

        cout << b << " " << d << endl;

       else

        cout << d << " " << b << endl;

      

    } else {

      cout << d << " ";

      if (b <= c)

        cout << b << " " << c << endl;

       else

        cout << c << " " << b << endl;

      

    }

  } else if (b <= a && b <= c && b <= d)

    cout << b << " ";

    // Repeat the process for b as the smallest number.

   else if (c <= a && c <= b && c <= d)

    cout << c << " ";

    // Repeat the process for c as the smallest number.

   else

    cout << d << " ";

    // Repeat the process for d as the smallest number.

  

  return 0;

}

在编译和运行这个程序之后,我们可以通过输入四个整数来测试它,并按从小到大的顺序输出它们。这是一个很好的练习,可以让我们更深入地了解C++编程语言,并提高我们的计算机技能。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复