C++ 实例 - 判断三个数中的最大数

C++ 教程 · 2019-02-26 11:58:56

通过屏幕我们输入三个数字,并找出最大的数。

实例 - 使用 if

#include <iostream> using namespace std; int main() { float n1, n2, n3; cout << "请输入三个数: "; cin >> n1 >> n2 >> n3; if(n1 >= n2 && n1 >= n3) { cout << "最大数为: " << n1; } if(n2 >= n1 && n2 >= n3) { cout << "最大数为: " << n2; } if(n3 >= n1 && n3 >= n2) { cout << "最大数为: " << n3; } return 0; }

以上程序执行输出结果为:

请输入三个数: 2.3
8.3
-4.2
最大数为: 8.3

实例 - 使用 if...else

#include <iostream> using namespace std; int main() { float n1, n2, n3; cout << "请输入三个数: "; cin >> n1 >> n2 >> n3; if((n1 >= n2) && (n1 >= n3)) cout << "最大数为: " << n1; else if ((n2 >= n1) && (n2 >= n3)) cout << "最大数为: " << n2; else cout << "最大数为: " << n3; return 0; }

以上程序执行输出结果为:

请输入三个数,以空格分隔: 2.3
8.3
-4.2
最大数为: 8.3

实例 - 使用内嵌的 if...else

#include <iostream> using namespace std; int main() { float n1, n2, n3; cout << "请输入三个数: "; cin >> n1 >> n2 >> n3; if (n1 >= n2) { if (n1 >= n3) cout << "最大数为: " << n1; else cout << "最大数为: " << n3; } else { if (n2 >= n3) cout << "最大数为: " << n2; else cout << "最大数为: " << n3; } return 0; }

以上程序执行输出结果为:

请输入三个数,以空格分隔: 2.3
8.3
-4.2
最大数为: 8.3

点击查看所有 C++ 教程 文章: https://codercto.com/courses/l/18.html

查看所有标签

游戏人工智能编程案例精粹

游戏人工智能编程案例精粹

巴克兰德 (Mat Buckland) / 罗岱 / 人民邮电出版社 / 2008年06月 / 55.00元

《游戏人工智能编程案例精粹》适合对游戏AI开发感兴趣的爱好者和游戏AI开发人员阅读和参考。一起来看看 《游戏人工智能编程案例精粹》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具