21xrx.com
2025-03-30 01:48:07 Sunday
文章检索 我的文章 写文章
C++编写三个数比较大小的程序
2023-07-05 10:19:02 深夜i     18     0
C++ 编程 比较大小 程序 算法

C++编程语言非常流行,因为它的速度很快,并且被广泛用于许多不同的应用程序。编写基本的程序可以帮助您了解该语言,并获得有关计算机编程的更深入的了解。在本文中,我们将介绍如何编写一个简单的C++程序来比较三个数字的大小。

首先,让我们来编写一个程序,询问用户输入三个数字,然后按照大小顺序将它们排列。在这个程序中,我们将使用一些逻辑运算符和条件语句来确定数字的大小关系。

以下是C++程序:

#include<iostream>
using namespace std;
int main()
{
  int num1, num2, num3;
  cout <<"Enter the first number: "; 
  cin >>num1;
  cout <<"Enter the second number: "; 
  cin>> num2;
  cout <<"Enter the third number: "; 
  cin >> num3;
  
  if(num1>num2 && num1>num3)
  {
    cout<< num1 <<" is the largest number."<< endl;
    if(num2>num3)
    
      cout<< num3 <<" is the smallest number."<< endl;
      cout<< num2 <<" is the middle number."<< endl;
    
    else
    
      cout<< num2 <<" is the smallest number."<< endl;
      cout<< num3 <<" is the middle number."<< endl;
    
  }
  else if(num2>num1 && num2>num3)
  {
    cout<< num2 <<" is the largest number."<< endl;
    if(num1>num3)
    
      cout<< num3 <<" is the smallest number."<< endl;
      cout<< num1 <<" is the middle number."<< endl;
    
    else
    
      cout<< num1 <<" is the smallest number."<< endl;
      cout<< num3 <<" is the middle number."<< endl;
    
  }
  else if(num3>num1 && num3>num2)
  {
    cout<< num3 <<" is the largest number."<< endl;
    if(num1>num2)
    
      cout<< num2 <<" is the smallest number."<< endl;
      cout<< num1 <<" is the middle number."<< endl;
    
    else
    
      cout<< num1 <<" is the smallest number."<< endl;
      cout<< num2 <<" is the middle number."<< endl;
    
  }
  else
  
    cout<< "Cannot determine the largest number."<< endl;
  
  return 0;
}

在这个程序中,我们使用了三个变量num1、num2和num3来存储用户输入的数字。然后,我们将这些数字与if语句中的条件进行比较,以确定各个数字之间的大小关系。在每个if语句中,我们使用嵌套if和else语句来进一步排列数字。

我们可以尝试使用上面的代码并执行该程序,输入三个数字并查看程序的输出。

通过编写这个程序,我们学会了一些基本的C++语言语法,例如变量、if语句、嵌套if和else语句。 C++是一种功能强大的语言,可以做很多事情,所以继续学习它将会给您带来许多挑战和愉快的经验。

  
  

评论区

请求出错了