c语言while和for转换,新手提问 关于C语言for语句转while语句

#include 

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 

{ 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 

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 

{ 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 ) ;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值