-
Sentinels
This is a very basic program i wrote. At first i had the total=0 and it was giving the incorrect answer so i changed the total to =1 and now it works fine can some one tell me why the total would be set to 1 at the start of the code. Thnx.
#include<stdio.h>
#include<conio.h>
void main(void)
{
int count;
float salary, total, average;
count=0;
total=1;
salary=0;
printf("THIS PROGRAM ACCEPTS A NUMBER OF SALARIES");
printf("\nAND PRINTS THE AVERAGE SALARY TOGETHER");
printf("\nWITH HOW MANY SALARIES WERE ENTERED\n");
while( salary != -1)
{
printf("\nENTER SALARY:");
scanf("%f",&salary);
total=total+salary;
count = count + 1;
}
count = count -1;
average= total / count;
printf("\nNUMBER OF SALARIES ENTERED ARE: %d",count);
printf("\nAVERAGE SALARIES %5.2f",average);
getch();
}
-
Few things, about your code:
>>void main(void)
main always returns int, so change it to int main() and then returns an value at the end of the program
>>total=total+salary;
Well, this is correct but don't work hard, you have the += operator, so total += salary is correct :)
>>count = count + 1;
same here you can an operator called ++, you can do this count++;
>>count = count -1;
same here you can use the -= operator, so you can do this count -= 1;
your program works even if total is set to zero, try it by yourself :)
Code:
#include<stdio.h>
#include<conio.h>
int main(void)
{
int count;
float salary, total, average;
count=0;
total=0;
salary=0;
printf("THIS PROGRAM ACCEPTS A NUMBER OF SALARIES");
printf("\nAND PRINTS THE AVERAGE SALARY TOGETHER");
printf("\nWITH HOW MANY SALARIES WERE ENTERED\n");
while( salary != -1)
{
printf("\nENTER SALARY:");
scanf("%f",&salary);
total += salary;
count++;
}
count = count -1;
average= total / count;
printf("\nNUMBER OF SALARIES ENTERED ARE: %d",count);
printf("\nAVERAGE SALARIES %5.2f",average);
getch();
return 0;
}
Also, try don't using conio.h it's not standard.
-
Thnx for the help Vber. For some reason when i run it with the total =0, just say i enter 2.00 five times it outputs the average as 1.80
-
Ahh this is the problem :o
add <math.h> in your document by using #include <math.h>
and change this line of code:
Code:
printf("\nAVERAGE SALARIES %5.2f",ceil(average));
-
Thnx again for the help its running much better.:)