21xrx.com
2024-09-20 00:38:45 Friday
登录
文章检索 我的文章 写文章
C++程序:四个数大小比较及降序排列输出
2023-07-05 21:52:07 深夜i     --     --
C++程序 四个数 大小比较 降序排列输出

在程序设计中,比较和排序是常见的操作。本文将介绍一个使用C++编写的程序,实现四个数的大小比较和降序排列输出。

首先,我们需要输入四个数,可以使用C++中的`cin`函数完成。代码如下:


#include <iostream>

using namespace std;

int main() c

接下来,我们需要进行大小比较。使用C++中的`if`语句可以判断两个数的大小关系。比较的具体方法是将两个数进行比较,如果一个大于另一个,则交换它们的值。代码如下:


if (a < b)

  int temp = a;

  a = b;

  b = temp;

if (a < c)

  int temp = a;

  a = c;

  c = temp;

if (a < d)

  int temp = a;

  a = d;

  d = temp;

if (b < c)

  int temp = b;

  b = c;

  c = temp;

if (b < d)

  int temp = b;

  b = d;

  d = temp;

if (c < d)

  int temp = c;

  c = d;

  d = temp;

最后,我们需要将四个数按照降序排列输出。使用C++中的`cout`函数可以输出四个数的值。代码如下:


cout << "降序排列输出结果:" << endl;

cout << a << " " << b << " " << c << " " << d << endl;

完整的程序代码如下:


#include <iostream>

using namespace std;

int main() {

  int a, b, c, d;

  cout << "请输入四个数:";

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

  

  if (a < b)

    int temp = a;

    a = b;

    b = temp;

  

  if (a < c)

    int temp = a;

    a = c;

    c = temp;

  

  if (a < d)

    int temp = a;

    a = d;

    d = temp;

  

  if (b < c)

    int temp = b;

    b = c;

    c = temp;

  

  if (b < d)

    int temp = b;

    b = d;

    d = temp;

  

  if (c < d)

    int temp = c;

    c = d;

    d = temp;

  

  

  cout << "降序排列输出结果:" << endl;

  cout << a << " " << b << " " << c << " " << d << endl;

  

  return 0;

}

以上就是四个数大小比较及降序排列输出的C++程序。通过这个程序,大家可以学习到如何使用`if`语句进行大小比较和值交换的方法,同时也可以掌握如何使用`cout`函数进行输出。希望本文的内容能够对大家有所帮助。

  
  

评论区

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