gingikid gingikid - 1 month ago 8
C++ Question

If/else if loop 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;

}
}

Answer

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.

Comments