I can't figure out why this code won't work. I'm trying to write a program where depending on the user's income, it will place them in a tax bracket. However, I can only get it to output 33% and 35%. What am I doing wrong?
I'm glad I could help! I remember when I first started out learning to code -- and I remember the people who helped me, so it's my time to return the favor!
- don't put upper and lower bounds in your if statements. It's redundant and error prone.
example... What bracket do you get if their income is 15099.5?
1 2 3 4
if ((income >= 0.0) && (income <= 15099.0)) // not this one...
bracket=10;
if ((income >=15100.0) && (income <= 61299.0)) // and not this one either
bracket=15;
The better way to do this is to have one comparison value in the if statement, and have 'else' take care of the exclusion work:
If I do it this way though, wouldn't that give me a very error prone output, also? For example, you used the code:
1 2
elseif(income < 61300)
bracket = 15;
How does the computer know whether I'm in the 10% bracket or the 15% bracket? Because less than 61,300 can range anywhere from 0 to 61,300 which also protrudes on the 10% bracket range of 0 to 15,100. How does this work?
I guess the computer checks in the order that you wrote your code. So it'll check first if it's in the range 10%. Remember you are using 'else if,' which means your program will skip past all the 'else if,' once one of the 'if' is true. That's why you use 'else if,' it's tied to your first 'if' statement and only goes to the next line if it's false, unlike the current model, which runs 6 'if' at a time and the 6 have the possibility of being true.
The template is
if statement
else if statement(statement above is false)
else do this (all statements are false)
The else keyword means the following will run only if the previous if statement was false.
Example:
1 2 3 4 5 6 7 8
if(foo == 5)
{
cout << "this will print only if foo is equal to 5";
}
else
{
cout << "this will print only if foo does not equal 5";
}
When combined with another if (elseif), the following if only runs if the else runs... and the else only runs if the previous if was false. So:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
if(foo < 5)
{
cout << "foo is less than 5";
}
elseif(foo < 10)
{
cout << "the else ensures that foo is not less then 5" << endl
cout << "and the if statement ensures that foo is less than 10" << endl;
cout << "therefore this only runs if foo is >= 5 and < 10";
}
else
{
cout << "foo is >= 10";
}
It would also help stylistically to indent your code so that you can visually tell which code is being tied to which if statement. something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
if(foo < 5)
{
cout << "foo is less than 5";
}
elseif(foo < 10)
{
cout << "the else ensures that foo is not less then 5" << endl
cout << "and the if statement ensures that foo is less than 10" << endl;
cout << "therefore this only runs if foo is >= 5 and < 10";
}
else
{
cout << "foo is >= 10";
}