Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If/else if always goes to else statement

I'm trying to make a function that determines commission based on user entered amount. It takes a user entered double and uses it to determine which equation it is used in. But the code I wrote always goes to the else statement, and I am not sure what is wrong with my conditions.

double calculate(double s)
{
    double c;
    if (s > 300,000)
    {
        c = 25,000 + (0.15 * (s-300,000));
        cout << "went to if" << endl;
        return c;

    }

    else if (300,000 > s && s > 100,000)
    {
        c = 5,000 + (0.10 * (s-100,000));
        cout << "went to else if" << endl;
        return c;

    }

    else
    {
        c = 0.05 * s;
        cout << "went to else" << endl;
        return c;

    }
} 
like image 676
gingikid Avatar asked Oct 23 '16 20:10

gingikid


People also ask

Should if statements always have an else?

An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.

Do you have to end an else if statement with an else?

After executing the statements following Then , ElseIf , or Else , execution continues with the statement following End If . The ElseIf and Else clauses are both optional. You can have as many ElseIf clauses as you want in an If ... Then ...

Does else execute after ELSE IF?

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to false , and the current elseif expression evaluated to true .

Why is my else if statement not working?

If you are getting an error about the else it is because you've told the interpreter that the ; was the end of your if statement so when it finds the else a few lines later it starts complaining. A few examples of where not to put a semicolon: if (age < 18); if ( 9 > 10 ); if ("Yogi Bear".


1 Answers

s > 300,000 is a comma expression, equivalent to (s > 300),000. The value of a comma expression is the value of the last one in the list, here 000. Which evaluates as false when converted to bool.

You can write that as

if( s > 300'000 )

or, if the compiler doesn't support that newfangled notation, as just

if( s > 300000 )

Or you can define

double const k = 1000;

and write

if( s > 300*k )

And similarly for the 25 000, 100 000 and 5000 literals.

like image 147
Cheers and hth. - Alf Avatar answered Sep 22 '22 06:09

Cheers and hth. - Alf