MODE —— 计算10个分数的平均值(知识点: 数组 变长数组)
數(shù)組是一個(gè)數(shù)目固定,類型相同的數(shù)據(jù)項(xiàng),數(shù)組中的數(shù)據(jù)項(xiàng)稱為元素。數(shù)組中的元素都是int、long、或者其他類型。
聲明一個(gè)數(shù)組時(shí),要給編譯器提供為數(shù)組分配內(nèi)存所需要的所有信息,包括值的類型(決定每個(gè)元素需要的字節(jié)數(shù))和數(shù)組維(指定了元素的個(gè)數(shù))。
數(shù)組占用的字節(jié)數(shù)是元素個(gè)數(shù)乘以每個(gè)元素的字節(jié)數(shù)。
問(wèn)題描述:
????? ? 使用數(shù)組可以存儲(chǔ)所有要平均的分?jǐn)?shù),即存儲(chǔ)所有分?jǐn)?shù),以便重復(fù)使用它們。計(jì)算10個(gè)分?jǐn)?shù)的平均值。
運(yùn)行結(jié)果:
? ??
代碼部分:? ??? ??
#include <stdio.h> int main(void) {int grades[10]; //Arrey storing 10 valuesunsigned int count = 10; //Number of values to be readlong sum = 0L; //Sum of the numberfloat average = 0.0f; //Average of the numberunsigned int i = 0; //Out loop printf("\nEnter the 10 grades:\n"); //Prompt for the input//Read the ten numbers to be averagedfor(i = 0;i < count; ++i){printf("%2u>",i+1);scanf("%d",&grades[i]);//Read a gradesum += grades[i]; //Add it to sum}average = (float)sum/count; //Calculate the acerageprintf("\nAverage of the ten grades entered is : %.2f\n",average);return 0; }代碼說(shuō)明:
????? ? 聲明一個(gè)包含10個(gè)整數(shù)的數(shù)組grades[10],
????????count變量是unsigned int 類型,因?yàn)樗仨毞秦?fù)。
????? ? 接下來(lái),用一個(gè)for循環(huán)讀入數(shù)值且累加它們。
????? ? 計(jì)算平均值的方法用sum除以分?jǐn)?shù)的個(gè)數(shù)count,count的值是10。
變長(zhǎng)數(shù)組運(yùn)行結(jié)果:
變長(zhǎng)數(shù)組代碼部分:
#include <stdio.h> int main(void) { //如果定義了_STDC_NO_VLA_ 符號(hào),printf()語(yǔ)句和后面的exit()語(yǔ)句就會(huì)包含在程序中。 //如果不支持變長(zhǎng)數(shù)組,但把這段代碼放在main()的開(kāi)頭,printf()函數(shù)調(diào)用就會(huì)心事一個(gè)消息,并立即結(jié)束程序。 #ifdef _STDC_NO_VLA_printf("Variable length arrays are not supported!\n");exit(1); #endifsize_t nGrades = 0; //Nmuber of gradesprintf("Enter the number of grades:");scanf("%zd",&nGrades);int grades[nGrades]; //Arrey storing 10 valueslong sum = 0L; //Sum of the numberfloat average = 0.0f; //Average of the numberprintf("\nEnter the %zd grades:\n",nGrades); //Prompt for the inputunsigned int i = 0;//Read the ten numbers to be averagedfor(i = 0;i < nGrades; ++i){printf("%2u>",i+1);scanf("%d",&grades[i]);//Read a gradesum += grades[i]; //Add it to sum}average = (float)sum/nGrades; //Calculate the acerageprintf("\nAverage of the %d grades entered is : %.2f\n",nGrades,average);return 0; }總結(jié)
以上是生活随笔為你收集整理的MODE —— 计算10个分数的平均值(知识点: 数组 变长数组)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: MODE —— 输入一个数字,求从1加到
- 下一篇: MODE —— 两个人在计算机上玩圈叉游