C语言:输入数值求平均数(T&F)

C语言求平均数

1.算法思想

  1. 算法:average=sum/count;
  2. 可以用循环实现数据输入
  3. 可以用数组实现输入输出。

2.代码分析

  1. 错误代码
#include
int main()
{

	int num;
	int count=0;
	int sum=0;
	printf("please input number:");
	scanf("%d",&num);
    while(num==1){
	sum+=num;
	
	scanf("%d",&num);
	count++;
    }
	printf("count is %d\n",count);
	printf("average is %f\n",1.0*sum/count);
	return 0;
}

输出:

please input number:1 2 3
count is 1
average is 1.000000

--------------------------------
Process exited after 3.33 seconds with return value 0
请按任意键继续. .

分析:循环只进行一次直接输出结果;

  1. 错误代码
#include
int main()
{

	int num;
	int count=0;
	int sum=0;
	printf("please input number:");
	scanf("%d",&num);
    while(num!=-1){
	sum+=num;
	count++;
	scanf("%d",&num);	
    }
	printf("count is %d\n",count);
	printf("average is %f\n",1.0*sum/count);
	return 0;
}

输出结果:

please input number:1 2 3
q

分析:这里光标一直在闪但不输出结果,

关系表达式中,非0值(正数与复数)表示“真”,“0”值表示“假”。

  1. 错误代码
#include
int main()
{
	int num;
	int sum=0;
	int ave;
	int count=0;
	printf("please input number:");
	while(scanf("%d",&num)!=-1){
		sum+=num;
		count++;
	
	} 
	ave=sum/count;
	printf("count is %d\n",count);
	printf("ave is %d",ave);
}

输出结果:

please input number:1 2 3
q

分析:这里光标一直在闪但不输出结果。

  • 正确代码

  • while循环

#include
int main()
{
	int num;
	int sum=0;
	float ave;
	int count=0;
	printf("please input number:");
	while(scanf("%d",&num)==1){
		sum+=num;
		count++;	
	} 
	ave=1.0*sum/count;
	printf("count is %d\n",count);
	printf("ave is %f",ave);
}
输出结果:
please input number:0 1 2 3 4 5
q
count is 6
ave is 2.500000

分析:这次将数据输入嵌套在while循环中,结果输出正确.

  • do-while 循环
#include
int main()
{
 	float  aver;
	int  num;
	int count=0;
	float sum=0;
	printf("please input number: ");
	
	do{	   
	   scanf("%d",&num);
  	   if(num!=-1){ 
	   sum+=num;
	   count++; 	                   
       }
	} while(num!=-1);
 	aver=sum/count;
 	printf("count is %d\n",count);
 	printf("average is %f\n",aver);
   // printf("average is %f\n",1.0*sum/count);
	return 0;	
 }
输出结果:
please input number:   1 2 3 3
-1
count is 4
average is 2.250000

--------------------------------
Process exited after 12.69 seconds with return value 0
请按任意键继续.

分析:do-while 输出结果正确。

3. 总结

搞混了条件表达式的值,!=-1在这里的意思就是当不等于-1时条件表达式的值为真,当等于-1时,条件表达式的值为假,这里-1,0也好,代表的只是本身,不代表整体条件表达式的值。

你可能感兴趣的:(C,Language)