首页 > 解决方案 > 在 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).";

标签: c++if-statement

解决方案


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。


推荐阅读