+ 1

How to make a program output which number is the maximum and minimal?

Hello. I understand that in this code line (a>b)?cout<<a:cout<<b; outputs a if a>b. But I'd like to understand what some things in this code line do. Why is a ? needed after(a>b) Why do we need a colon after a in <<a:cout<<b; Why doesn't b need a colon too? Isn't this code also saying to the program to output b? Thanks in advance! The program as it follows: #include <iostream> using namespace std; int main() { double a, b; cout << "Enter value for a:" << endl; cin >> a; cout << "Enter value for b:" << endl; cin >> b; cout << "a+b=" << a+b << endl; cout << "a-b=" << a-b << endl; cout << "a*b=" << a*b << endl; cout << "(a+b)/2=" << (a+b)/2 << endl; cout << "the max is "; (a>b)?cout<<a:cout<<b; cout << endl; cout << "the min is "; (a<b)?cout<<a:cout<<b; cout << endl; system("pause"); }

20th Oct 2017, 6:31 PM
Melonie Cardiff
Melonie Cardiff - avatar
3 odpowiedzi
+ 3
It's just the syntax. It's how it's written. It's a shortcut way of writing an if else statement. Why do we need to write it with a ? and a : between both statements? Because who ever wrote the language thought it was a good idea. And I think it's pretty simple. Basically, it's because whoever wrote the language said so. (int1 < int2) ? cout << "condition is true" : cout << "condition is false"; This could also be written as: if(int1 < int2) { cout << "condition is true"; } else { cout << "condition is false"; } Whoever wrote the language simply wanted to give us a shorter way to write things like this. The ? tells us to check the previous condition in this case, and the colon is used to separate the "if true" condition from the "if false" condition.
20th Oct 2017, 6:47 PM
Christian Barraza
Christian Barraza - avatar
+ 7
This is called ternary operator. it's used to check condition just like if-else. EXAMPLE : if statement : if(a < 2) b = 5; else b = 4; Equivalent ternary statement : b = (a < 2) ? 5 : 4 EDIT: You can use if else for the given code as follows : if (a > b) cout << a; else cout << b;
20th Oct 2017, 6:39 PM
Shamima Yasmin
Shamima Yasmin - avatar
0
Personally, the statement for max should have been coded: cout<<(a>b)?a:b; It makes use of the ternary result.
20th Oct 2017, 7:47 PM
John Wells
John Wells - avatar