整型变浮点型以及循环控制

计算班级平均数

计数控制的循环

int main()
{
     
	unsigned int counter;
	int grade;
	int total;
	float average;
	total = 0;
	counter = 1;
	while( counter <= 4)//需要计算的数是确定的
	{
     
		printf("enter grade:  ");
		scanf("%d",&grade);
		total = total + grade;
		counter = counter + 1;

	}
	average = total/4.0;//可尝试写成4 
	//会出现average怎么样都无法出现正确的数。因为4是整型,total也是整型
	printf("class average is %f\n",average);
}

标记控制的循环
循环体结构改为

while(grade != -1)
{
     	total = total + grade;
	counter = counter + 1;
	printf("enter grade,-1 to the end")
	scanf("%d",&grade);
}
if(counter != 0)
{
     	average = total/counter;
	printf("class average is %.2f\n",average);
}
else{
     //if no grades were entered, output messege
{
     	puts("no grades were entered");}

通过标记某个条件,来结束循环
还可以强行转换数据类型

average  = (float)total/counter

你可能感兴趣的:(笔记,c语言)