Juan Antonio Zaratiegui Vallecillo
11/3/2008 3:52:00 PM
Juan Antonio Zaratiegui Vallecillo wrote:
> yuanshuaisd@yahoo.cn wrote:
>> #include<stdio.h>
>> int main()
>> {
>> int n=1;
>
> 'num' initialised to 1, and reinitialized later in the loop, you may
> just intialise it once
No, this comment is wrong.
>
>> int average;
>> int num;
>> int sum;
>
> 'sum' is not initialised
>
>> for(n=1;num != 9999;n++){
Shouldn't it be:
while ( num != 9999 ) {
?
>> printf("Enter a integer:\n");
>> scanf("%d",&num);
>
> 'scanf' return value is not checked for errors
>
>>
>> sum = sum + num;
>> }
>>
>> average = sum / n;
>
> 'average' is integer, so the result will be such that:
> result<= real average< result+1
>
>> printf("average is %d",average);
>>
>> return 0;
>> }
>> why the program end in a wrong result
>
> When you add anything to an undefined value (not initialised) the result
> is undefined behaviour. That is, you may even get the result you
> expected. Now. But not later, specially if you are showing your program
> to another party.
>
> Best regards,
>
> Zara