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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jeremy C

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

    Code:
    // This program will read three (3) integers than display its numerical sequence.
    
    #include "std_lib_facilities.h"
    
    int main()
    {
    	cout << "This program will read three (3) integers of your choice and than\n";
    	cout << "display them in its numerical sequence.\n";
    	cout << "Please enter three (3) integers:\n";
    	int val1;
    	int val2;
    	int val3;
    	while (cin >> val1 >> val2 >> val3){
    		if (val1 <= val2 <= val3)
    			cout << val1<<", "<<val2<<", "<<val3<<'\n';
    		else if (val1 <= val3 <= val2)
    				cout << val1<<", "<<val3<<", "<<val2<<'\n';
    			else if (val2 <= val1 <= val3)
    					cout << val2<<", "<<val1<<", "<<val3<<'\n';
    				else if (val2 <= val3 <= val1)
    						cout << val2<<", "<<val3<<", "<<val1<<'\n';
    					else if (val3 <= val1 <= val2)
    							cout << val3<<", "<<val1<<", "<<val2<<'\n';
    						else if (val3 <= val2 <= val1)
    								cout << val3<<", "<<val2<<", "<<val1<<'\n';
    	}
    	keep_window_open();
    	return 0;
    }
    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.
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    because, say, 3 <= 1 <= 4 evaluates to
    (3<=1) <= 4 then to
    0 <= 4 that is true. Use || and && for multiple conditions.

    Comment

    • Jeremy C

      #3
      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

      Comment

      Working...