How to setup Ternary statement.....
Mar 1, 2015 at 3:03pm UTC
Im having problems trying to do a ternary statement when my code contains alot of if statements.
Ive got a chart of a tax schedule
0-100 is 0%
101-200 is 10%
201-300 is 20%
301-400 is 30%
401-500 is 40%
501-999 is 50%
ive named the variable I want to cout as Trate....
small example:
1 2 3 4
if (x>=0 && x<=100)
{
cout << Trate;
The if statement goes all the way to 999 and then cout's a Trate (tax rate)
How can I set up a ternary to shrinken the if statements I have ? It takes up nearly 20 lines.....
Mar 1, 2015 at 3:42pm UTC
Ternary expressions and if statements are two different things.
A ternary expression evaluates a condition and results in one of two possible values.
http://www.cplusplus.com/articles/1AUq5Di1/
I don't recommend ternary expressions for what you're trying to do. Nested ternary expression can get unreadable pretty quickly. Also, since a ternary operator results in an expression, you're going to find it hard to mix that with cout which is a statement.
cout << (x<=100)?0.10:(x<=200)?0.20:(x<=300)?0.30:(x<=400)?0.40:(x<=999)?0.50:0 ;
BTW, you don't specify what rate should be if x > 999. Note the 0 in the last ternary operator.
Last edited on Mar 1, 2015 at 3:42pm UTC
Topic archived. No new replies allowed.