-2
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 ;

I want to check my variables, but it doesn't work.

//Check inputs
if ( math , physics , chemistry , literature > 20 ){
    cout << "Error ... The score should be in range (0,20).";
ocrdu
  • 2,172
  • 6
  • 15
  • 22
  • My suggestion is that you make a generic function to get input, with a prompt and a limit as arguments. Then the function could iterate until the input is in the range requested and return the value then. Then call that function once for each input. – Some programmer dude Dec 23 '20 at 14:40
  • 1
    "it didn't worked" is not a problem description. What error did you get? You should explain the specific problem when writing a question. Anyway, this particular question is just a result of not having read enough about the language before writing code, sorry. – underscore_d Dec 23 '20 at 14:41
  • On another note, you forget to check against the lower bound (`0`). And is the input supposed to be a floating-point number or an integer? Is e.g. `12.34` a valid input? – Some programmer dude Dec 23 '20 at 14:42
  • It would be nice if we could do `if (std::ranges::any_of({ math, physics, chemistry, literature }, [](auto score){ return > 20; })` ... – Dietmar Kühl Dec 23 '20 at 14:51
  • ... and on other notes: always check input after reading if it was successful! – Dietmar Kühl Dec 23 '20 at 14:52

3 Answers3

6
if ( math , physics , chemistry , literature > 20 ){

While this is valid C++, it's almost definitely not doing what you want (see How does the Comma Operator work for more). Ordinarily you'd do what you're looking for like:

if ( math > 20 || physics > 20 || chemistry > 20 || literature > 20 ){

You can however, shorten this with a call to std::max:

if (std::max({math, physics, chemistry, literature}) > 20) {

This'll work since you only really care about the greatest value here. If the greatest value of the four is less than 20, then it means ALL are less than 20.

scohe001
  • 15,110
  • 2
  • 31
  • 51
0

The following code is allowed by the language:

if (math, physics, chemistry, literature > 20 ) {

It's a standard usage of the comma operator, but it does not give you the expected result.

You should rewrite it like this instead:

if (math > 20 || physics > 20 || chemistry > 20 || literature > 20) {

ocrdu
  • 2,172
  • 6
  • 15
  • 22
0

Instead of write if ( math , physics , chemistry , literature > 20 ) you should write:

if ( math > 20 || physics > 20 || chemistry > 20 || literature > 20 )
if you want to check if even just one element is bigger than 20;

if ( math > 20 && physics > 20 && chemistry > 20 && literature > 20 )
if you want to check if all the elements are bigger than 20.