-
Logic all wrong
This is what I got so far in my program:
Code:
#include <stdio.h>
#include <stdlib.h>
void main (void) {
int num, sum, valid, invalid;
float avg;
printf("Please enter a positive value or -1 to terminate the program:");
scanf("%d", &num);
while (num!=-1) {
sum=num+num;
valid++;
printf("Please enter a positive value or -1 to terminate the program:");
scanf("%d", &num);
}
avg=sum/(float)valid;
printf("sum=%d\n", sum);
printf("valid=%d\n", valid);
printf("avg=%.2f\n", avg);
}
When I compile I get no errors. When I run the executable though, the value of sum is one less than it should be, which in turn makes avg off as well. Where is my logic wrong?
-
>Where is my logic wrong?
This is a start:
main returns int, not void...ever.
>When I compile I get no errors.
I bet you get warnings though, you should pay attention to them.
Anyway, if you're taking the average of a list of numbers then you're going about it the wrong way. The sum is a running total, not the sum of the each number with itself:
Code:
#include <stdio.h>
int main ( void )
{
int sum = 0;
int num;
int i;
printf ( "Enter a list of numbers, -1 to quit: " );
fflush ( stdout );
for ( i = 0; scanf ( "%d", &num ) == 1 && num != -1; i++ )
sum += num;
printf ( "Sum: %d\n", sum );
printf ( "Numbers: %d\n", i );
printf ( "Average: %f\n", (double)sum / i );
return 0;
}
-
i'm not a proffessional but try this ...
Code:
int num, sum, valid=0, invalid;
Code:
do
{
sum=num+num;
valid++;
printf("Please enter a positive value or -1 to terminate the program:");
scanf("%d", &num);
}
while(num==-1);
-
Hi,
I don't really understand what you are trying to do with the program
Code:
while (num!=-1) {
sum=num+num;
valid++;
printf("Please enter a positive value or -1 to terminate the program:");
scanf("%d", &num);
}
if you are trying to take the average of what the user inputs, this won't work because you aren't keeping any values in memory. 'sum' is overwritten repeatedly. If you want to take the average, initialize 'sum' to 0, and then increment it by 'num'
For example:
Code:
sum = 0;
while (num!=-1)
{
sum+=num;
valid++;
printf("Please enter a positive value or -1 to terminate the program:");
scanf("%d", &num);
}
Hope this helps,
Ryan
-
Thanks everyone I forgot to intilize valid to 0. It now works.