Reputation: 1
In my homework, I've been asked to write a program using both if and switch statement to compare the net amount paid by a customer for the following details
Purchase Amount (100-200) then give 5% Discount.
Purchase Amount (200-500) then give 7.5% Discount.
Purchase Amount (500-800) then give 10% Discount.
Purchase Amount (Above 1000) then give 15% Discount.
This is something I could come up with, but while compliling it is given me error like
Line 10: error: case label does not reduce to an integer constant Line 13: error: case label does not reduce to an integer constant Line 17: error: expected expression before ':' token. Can anyone please help me with this. Am I not following the question correctly or there is something else I'm doing wrong
#include<stdio.h>
main()
{
int pa = 200;
float net;
printf("\n Enter purchased amount");
scanf("%d",&pa);
switch(pa)
{
case 1&&pa<=100:
net=pa;
break;
case pa>=101&&pa<=200:
net=pa-(5.00/100.00)*pa;
break;
default:
if(pa>=201&&pa<=500)
net=pa-(7.5/100.00)*pa;
if(pa>=501&&pa<=800)
net=pa-(10.00/100.00)*pa;
if(pa>=1000)
net = pa - (15.00/100.00)*pa;
break;
}
printf("\n the net amount to be paid is%f",net);
getch();
}
Upvotes: 0
Views: 288
Reputation: 127
For range related condition, it'd better to use if/else condition. switch/case is for constant value condition.
if (pa >= 1 && pa <= 100) {
net = pa;
} else if (pa>=101&&pa<=200) {
net=pa-(5.00/100.00)*pa;
} else if (pa>=201&&pa<=500) {
net=pa-(7.5/100.00)*pa;
} else if (pa>=501&&pa<=800) {
net=pa-(10.00/100.00)*pa;
} else if (pa>=1000) {
net = pa - (15.00/100.00)*pa;
} else {`<br/>
/* invalid pa handling */
}
Upvotes: 0
Reputation: 7132
if you use switch case, you must match against exact values (constants), otherwise,use cascaded if's
Just read how switch
/case
work
Upvotes: 0
Reputation:
case
label should be compile time constant.
You cannot give a variable inside case
label. Expression in label have to be evaluated at compile time.
If you want to branch during run time, use if-else
.
Upvotes: 5