C++ 程序:在 3 个数字中找出最大和最小
原文:https://www.studytonight.com/cpp-programs/cpp-find-largest-and-smallest-among-3-numbers-program
大家好!
在本教程中,我们将学习如何用 C++ 编程语言在用户输入的 3 个数字中找到最大和最小的数字。
这个程序利用这个例子演示了 cpp 编程语言中 if-else 块的流程。
代号:
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to find the Largest and the Smallest number among 3 numbers ===== \n\n";
//variable declaration
int n1, n2, n3, smallest, largest;
//taking input from the command line (user) all at once
cout << " Enter the three numbers : \n\n\n";
cin >> n1 >> n2 >> n3;
//assign initial value for comparison (as the undefined variables store a random value)
smallest = n1;
largest = n2;
//logic to find the Smallest and the Largest number - Remember, each variable stores only the latest value inserted into it.
if (n2 < smallest)
{
smallest = n2;
}
if (n3 < smallest)
{
smallest = n3;
}
if (n3 > largest)
{
largest = n3;
}
if (n2 > largest)
{
largest = n2;
}
cout << "\n\n The Smallest number among ( " << n1 << ", " << n2 << ", " << n3 << " ) is : " << smallest;
cout << "\n\n The Largest number among ( " << n1 << ", " << n2 << ", " << n3 << " ) is : " << largest;
cout << "\n\n\n";
return 0;
}
输出:
我们希望这篇文章能帮助你更好地理解如何使用 C++ 中的 if-else 块找到最小和最大的数字。如有任何疑问,请随时通过下面的评论区联系我们。
继续学习: