Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include<iostream>
using namespace std;
main()
{
    int a, b, c, d;
    cout << "Enter three numbers.";
    cin >> a >> b >> c;
    d = ( a>b ? a : b );
    cout << (d > c) ? d : c;
    return 0;
}



This program is returning value 0 for any of three value I enter. Any help will be really appreciated. Ty

What I have tried:

idk i have tried this code but the same issue

#include<iostream>
using namespace std;
main()
{
    int a, b, c;
    cout << "Enter three numbers.";
    cin >> a >> b >> c;
    cout << ((a>b ? a : b ) > c) ? (a>b ? a : b ) : c ;
    return 0;
}
Posted
Updated 7-Oct-20 20:10pm
Comments
KarstenK 8-Oct-20 3:21am    
you are mixing "business logic" and "ui" - that is bad style.

maybe you understand it someday. Til then ;-)

That is because how you are using the ?: operator in the cout. It's all about precedence of operators[^]. Bracket being one of the top most.

When you write:
C++
cout << (d > c) ? d : c;
d>c is evaluated as they are in brackets and the result of that is printed. So the values would be 0 or 1 always and none of the a,b,c values there.

A small change should work:
C++
#include<iostream>
using namespace std;

int main()
{
    int a, b, c, d;
    cout << "Enter three numbers.";
    cin >> a >> b >> c;
    d = ( a>b ? a : b );
    cout << (d > c ? d : c);
    return 0;
}

Moved the entire ?: inside the bracket which is intended.
 
Share this answer
 
v2
Comments
CPallini 8-Oct-20 2:02am    
5.
Sandeep already gave you the solution. If you want to stick to a 1-line code, then try:
C++
#include <iostream>
using namespace std;

int main()
{
    int a, b, c;
    cout << "Enter three numbers.";
    cin >> a >> b >> c;
    cout << ( a > b ? ( a > c ? a : c) : ( b > c) ? b : c) << endl;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900