提问者:小点点

在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).";

共3个答案

匿名用户

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,那么就意味着所有的值都小于20。

匿名用户

如果(数学,物理,化学,文学>20),而不是编写,您应该编写:

if(数学>20物理>20化学>20文献>20)
如果要检查是否仅有一个元素大于20;

if(数学>20物理>20化学>20文献>20)
如果要检查是否所有元素都大于20。

匿名用户

该语言允许使用以下代码:

<罢工> 如果(数学,物理,化学,文学>20){

这是逗号运算符的标准用法。但它并没有给你预期的结果。

您应该这样改写它:

如果(数学>20物理>20化学>20文献>20){