c++ - 在 if 条件下检查多个变量
问题描述
float math , physics ,literature , chemistry ;
cout << "Enter math score : ";
cin >> math ;
cout << "Enter physics score : ";
cin >> physics ;
cout << "Enter chemistry score : ";
cin >> chemistry ;
cout << "Enter literature score : ";
cin >> literature ;
我想检查我的变量,但它没有用....
//Check inputs
if ( math , physics , chemistry , literature > 20 ){
cout << "Error ... The score should be in range (0,20).";
解决方案
if ( math , physics , chemistry , literature > 20 ){
虽然这是有效的 C++,但它几乎肯定不会做你想做的事(请参阅逗号运算符如何工作以获取更多信息)。通常你会做你正在寻找的东西:
if ( math > 20 || physics > 20 || chemistry > 20 || literature > 20 ){
但是,您可以通过以下方式缩短此时间std::max
:
if (std::max({math, physics, chemistry, literature}) > 20) {
这会起作用,因为您只真正关心这里的最大价值。如果四个中的最大值小于 20,则意味着 ALL 小于 20。
推荐阅读
- julia - 如何在 Julia 1.0 中做 memoization 或 memoisation
- c# - 将任何 DateTime 值转换为 UTC
- kubernetes - Kong Ingress 控制器说明
- javascript - 在构建 angular-6 应用程序时遇到此错误,我该如何解决?
- python - 单击 Windows 应用程序并使用 pywinauto 输入文本
- c++ - 共享内存数组中两个单元格的差异(并发)
- javascript - 如何在 Node js 中同步使用串口?
- wcf - Web.config 未在 IIS 中用于 WCF
- php - .ttf 文件不起作用
- python - QtWebView 哪个版本的 HTML?