By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,991 Members | 1,917 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,991 IT Pros & Developers. It's quick & easy.

How Can I Compare More Than Two Values in an 'if' Function?

P: n/a
Expand|Select|Wrap|Line Numbers
  1. // This program will read three (3) integers than display its numerical sequence.
  2.  
  3. #include "std_lib_facilities.h"
  4.  
  5. int main()
  6. {
  7.     cout << "This program will read three (3) integers of your choice and than\n";
  8.     cout << "display them in its numerical sequence.\n";
  9.     cout << "Please enter three (3) integers:\n";
  10.     int val1;
  11.     int val2;
  12.     int val3;
  13.     while (cin >> val1 >> val2 >> val3){
  14.         if (val1 <= val2 <= val3)
  15.             cout << val1<<", "<<val2<<", "<<val3<<'\n';
  16.         else if (val1 <= val3 <= val2)
  17.                 cout << val1<<", "<<val3<<", "<<val2<<'\n';
  18.             else if (val2 <= val1 <= val3)
  19.                     cout << val2<<", "<<val1<<", "<<val3<<'\n';
  20.                 else if (val2 <= val3 <= val1)
  21.                         cout << val2<<", "<<val3<<", "<<val1<<'\n';
  22.                     else if (val3 <= val1 <= val2)
  23.                             cout << val3<<", "<<val1<<", "<<val2<<'\n';
  24.                         else if (val3 <= val2 <= val1)
  25.                                 cout << val3<<", "<<val2<<", "<<val1<<'\n';
  26.     }
  27.     keep_window_open();
  28.     return 0;
  29. }
I can't seem to get this exercise working properly. When I run it there are no errors, although it doesn't output the values in chronological order. Which is what I'd like it to do.

Any help would be much appreciated.

Jeremy C.
Nov 13 '10 #1
Share this Question
Share on Google+
2 Replies


100+
P: 687
because, say, 3 <= 1 <= 4 evaluates to
(3<=1) <= 4 then to
0 <= 4 that is true. Use || and && for multiple conditions.
Nov 13 '10 #2

P: n/a
Ah, thank you. For some reason I wasn't able to find both of those operators. I guess I didn't look hard enough.

Thanks again newb16
Nov 13 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.