this program will calculate your tax bracket by the entering your income and your marital status, s for single and m for married.
The program will prompt you to enter income, then marital status. However it does not calculate income tax owed, always displays $0.00. Any help would be appreciated. Thank you very much!
Here is my code so far:
int taxBracket (double income, char maritalStatus);
double calculateTax(double income, int taxBracket);
int main() {
double income;
char maritalStatus;
int taxBracketValue;
printf("Enter income: ");
scanf("%le", &income);
printf("Enter marital status (s for single, m for married): ");
scanf(" %c", &maritalStatus);
taxBracketValue = taxBracket(income, maritalStatus);
if(taxBracketValue == -1) {
printf("Invalid marital status.\n");
return 1;
}
double tax = calculateTax(income, taxBracketValue);
printf("Income tax is $%.2f\n", tax);
return 0;
}
int taxBracket(double income, char maritalStatus) {
if (maritalStatus == 's') {
if(income < 15000)
return 0;
else if (income >= 15000 && income < 50000)
return 1;
else if (income >= 50000 && income < 90000)
return 2;
else if (income >=90000 && income < 160000)
return 3;
else
return 4;
}
else if (maritalStatus == 'm') {
if (income < 30000)
return 0;
else if (income>= 30000 && income < 80000)
return 1;
else if (income>= 80000 && income < 140000)
return 2;
else if (income >= 140000 && income < 220000)
return 3;
else
return 4;
}
return -1;
}
double calculateTax(double income, int taXBracket) {
double tax = 0.0;
int taxBracket;
switch(taxBracket) {
case 0:
tax = 0.0;
break;
case 1:
tax = income * 0.10;
break;
case 2:
tax = income * 0.15;
break;
case 3:
tax = income * 0.23;
break;
case 4:
tax = income * 0.33;
break;
default:;
break;
}
return tax;
}
Code is hard to read when it's poorly formatted.
In
calculateTax()the local variabletaxBracketis uninitialized but you want to use the argument which is capitalized differently. This is your main issue, and your compiler should generate a warning for use of the uninitialized variable.The include for
scanf()andprintf()functions is missing.For small programs you can usually eliminate the prototypes by moving
main()to the bottom.(Not fixed) Business rules like
taxbracket()andcalculatetax()are subject to frequent change. They benefit from being expressed as data (tables) instead of code possible externalized (file, database, web service etc). In this case it also eliminates all theincome * ...duplication. This return early-pattern for the special cases often lead to concise code.You could refactor this, say, returning the rate, and let caller determine the tax amount by multiplying with
income:Leave out the
;indefault:;. The real power of a switch statements is realized when you switch on aenum. If you leave out the catch-alldefaultthe compiler can now tell if you are missing a case.and example run: