Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditional operator not giving correct output

We have an issue that I have been able to recreate with this sample code:

int main()
{
  double d = -2;
  // ...
  cout << "d: " << d << endl;
  cout << "-d: " << -d << endl;
  
  cout << "Conditional Operator (expect value 2): " << (d < 0)? -d : d;
  cout << endl;
  
  return 0;
}

The output is as follows:

d: -2
-d: 2
Conditional Operator (expect value 2): 1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s a problem of operator precedence. Use:

cout << "Conditional Operator (expect value 2): " << (d < 0? -d : d);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading