Hi,
First of all a great site ,Hope beginner's like me can learn from this forum
I have a problem whilst running the program:Below code runs fine but when I make some changes to it some issues crop up .Please have a look
Correct Code:
-------------------------------------------------------------------
Code:
/*Power charges calculator
0 - 200 units each unit 0.75
201-400 units -100 + 1 for each unit above 200
401 - 600 units -250 + 1.25 for each unit exceeding 400
601 and above -450 +1.5 for each unit exceeding 600*/
#include<stdio.h>
int main()
{
int units;
float charges;
printf("Please enter the number of units consumed rounded to the nearest number:");
scanf("%d",&units);
fflush(stdin);
if (units<=200)
charges = 0.75 * units;
else if (units<=400)
charges = (400-units)+100;
else if (units<=600)
charges = (600-units)*1.25 + 250;
else
charges = (units-600)*1.5 + 450;
printf("The charges for the current billing cycle is %.2f",charges);
getchar();
}
--------------------------------------------------------------------
The above code works perfectly fine but if I do add a printf at the end of every statement it throws up the following error : syntax error before "else"
----------------------------------------------------------------
Code:
/*Power charges calculator
0 - 200 units each unit 0.75
201-400 units -100 + 1 for each unit above 200
401 - 600 units -250 + 1.25 for each unit exceeding 400
601 and above -450 +1.5 for each unit exceeding 600*/
#include<stdio.h>
int main()
{
int units;
float charges;
printf("Please enter the number of units consumed rounded to the nearest number:");
scanf("%d",&units);
fflush(stdin);
if (units<=200)
charges = 0.75 * units;
printf("The charges for the current billing cycle is %.2f",charges);
else if (units<=400)
charges = (400-units)+100;
printf("The charges for the current billing cycle is %.2f",charges);
else if (units<=600)
charges = (600-units)*1.25 + 250;
printf("The charges for the current billing cycle is %.2f",charges);
else
charges = (units-600)*1.5 + 450;
printf("The charges for the current billing cycle is %.2f",charges);
getchar();
}
--------------------------------------------------------------
My issue when the code throws up an error before the else clause due to the printf statement .Provided the if statement is true it should run the printf statement (even those in the else if clauses) because as far as my understanding goes, with the curling braces all the else statement controls is the next line rest of the lines should be executed without any dependence on the else if statement.
My understanding is the code should run but will probably print out the printf under all the conditions with no dependence of the if or else if statements.Please do help me out and let me know why this is not the case.
Regards