#include <stdio.h> int main() { double n, total ; /* a number is input into n and add to total */ double average ; /* average of compute by total divide by i */ int i ; total = 0 ; printf( "\nCompute the average of some numbers between 0 and 100 \n" ); for( i = 0 ; ; i++ ) { printf( "please input a number (-1 to stop input) :> ") ; scanf( "%lg", &n ) ; if ( n > 100 ) { printf("Value input is too large. It is ignore!\n"); i-- ; continue; } if ( n < -1 ) { printf("Value input is too small. It is ignore!\n"); i-- ; continue; } if ( n == -1 ) break ; total = total + n ; } if ( i == 0 ) { printf("No number is input! Nothing to compute the average!\n"); } else { average = total / i ; printf( " The average of all the numbers are : %g\n\n" , average ) ; } }
将上述代码中的for语句转换为while语句 这是计算0-100之间数值平均数的一个小程序 以下是我改写后的代码 运行后如果分别输入1,2,3 则可以得到正确答案 如果先输入大于100和小于-1的数 再输入正确范围的数值则运算有误 请各位前辈看看我改写的代码中哪里出错了
#include <stdio.h> int main() { double n, total ; /* a number is input into n and add to total */ double average ; /* average of compute by total divide by i */ int i ; total = 0 ; printf( "\nCompute the average of some numbers between 0 and 100 \n" ); i = 0 ; while(1) { printf( "please input a number (-1 to stop input) :> ") ; scanf( "%lg", &n ) ; if ( n > 100 ) { printf("Value input is too large. It is ignore!\n"); --i ; continue; } if ( n < -1 ) { printf("Value input is too small. It is ignore!\n"); --i ; continue; } if ( n == -1 ) break; { total = total + n ; i++; } if ( i == 0 ) { printf("No number is input! Nothing to compute the average!\n"); } else { i++ ; total = total + n ; average = total / i ; } } printf( " The average of all the numbers are : %g\n\n" , average ) ; }
wwpbjing
相关分类