Work out a tax that has several bands.
What to build
A chain of conditions in which each band is only partly taxed.
Requirements
- The first 10000 is not taxed.
- The next 20000 is taxed at 10%.
- Anything above 30000 is taxed at 20%.
- Print the tax with two decimals, or
invalidfor a negative income.
Input
One whole number: the income.
Output
One line.
Constraints
The income is from -1000 to 100000000.
Example
Input:
5000
Output:
0.00
Why it works
Only the part of the income inside a band is taxed at that band's rate, so going over a limit never makes someone worse off.
Examples
Example 1 · Input
5000
Expected output
0.00
Example 2 · Input
20000
Expected output
1000.00
Hints
Hint 1
Deal with the invalid case first.
Hint 2
Work from the top band down, and tax only the part of the income in each band.
Hint 3
Use a double for the tax.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int income;
scanf("%d", &income);
if (income < 0) {
printf("invalid\n");
return 0;
}
double tax;
if (income <= 10000) {
tax = 0;
} else if (income <= 30000) {
tax = (income - 10000) * 0.10;
} else {
tax = 20000 * 0.10 + (income - 30000) * 0.20;
}
printf("%.2f\n", tax);
return 0;
}