1. 程式人生 > >MODE ——計算了 任意多個數字的平均值(知識點:for的迴圈)

MODE ——計算了 任意多個數字的平均值(知識點:for的迴圈)

問題描述:

輸入浮點數值 判斷是否繼續輸入 輸出N時候 退出for迴圈 計算出來 輸入所有數字的平均值

執行結果:

[[email protected] C]# ./a.out 

This program calculates the average of any number of values.
Enter a value:1
Do you want to enter another value?(Y or N):y

Enter a value:2
Do you want to enter another value?(Y or N):y

Enter a value:3
Do you want to enter another value?(Y or N):n

The average is 2.00

程式碼部分:

#include <stdio.h>
#include <ctype.h>
int main(void)
{
	char answer = 'N';
	double total = 0.0;
	double value = 0.0;
	unsigned int count = 0;
	
	printf("\nThis program calculates the average of any number of values.");
//for 迴圈中的break 的使用	
	for (;;)
	{	
		printf("\nEnter a value:");
		scanf(" %lf",&value);
		total += value;
		++count;
		
		printf("Do you want to enter another value?(Y or N):");
		scanf(" %c",&answer);
		if(tolower(answer) == 'n')
			break;
	}	
	printf("\nThe average is %.2lf\n",total/count);
	return 0;
}