可以注意下sizeof獲取數(shù)組長(zhǎng)度的問(wèn)題
#include <stdio.h>
//計(jì)算考試的總分
static int totalGrade(int score[10])
{
? ? int sum = 0;
? ? int j;
? ? for(j=0; j<10; j++)
? ? {
? ? ? ? sum += score[j];
? ? ? ??
? ? }
? ?
? ? return sum;
}
//最高分
void highGrade(int score[10])
{
? ? int contrast = 0;
? ? int i;
? ? for(i=0;i<10;i++)
? ? {
? ? ? ? if (score[i] > contrast)
? ? ? ??
? ? ? ? ? ? contrast = score[i];
? ?
? ? }
? ? ?printf("最高分?jǐn)?shù)為%d\n", contrast);
? ??
}
//最低分
void lowGrade(int score[10])
{
? ? int i,j;
? ? for(i=9; i>=0; i--)
? ? {
? ? ? ? for(j=0;j<i;j++)
? ? ? ? {
? ? ? ? ? ? if(score[j]>score[j+1])
? ? ? ? ? ? {
? ? ? ? ? ? int temp;
? ? ? ? ? ? temp = score[j];
? ? ? ? ? ? score[j] = score[j+1];
? ? ? ? ? ? score[j+1] = temp;
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? ?printf("最底分?jǐn)?shù)為%d\n",score[0]);
? ??
? ??
}
//平均分
void argGrade(int score[10], int length)
{
? ? int arg;
? ? int totalgrade = totalGrade(score);
? ? /*? int cnt = (sizeof(score) / sizeof(score[0])); //數(shù)組作為參數(shù)傳到函數(shù)內(nèi)部時(shí)是返回指針大小不是數(shù)組本身
? ? ? ? printf("%d\n",cnt);
? ? ? ? sizeof(score)其實(shí)計(jì)算的是指針變量score的類(lèi)型的大小。指針score的類(lèi)型是指向整數(shù)類(lèi)型的指針? ? ?*/
? ??
? ? /* sizeof(arr) / sizeof(arr[0])
? ? 但這種一般是在主函數(shù)里面才能求,如果arr作為參數(shù)傳遞給子函數(shù)的話(huà),數(shù)組名將會(huì)轉(zhuǎn)換成指針形式傳遞,因此這種求解就有錯(cuò)誤了。*/
? ?
? ? /*? 數(shù)組是 int 型的,每個(gè)元素占 4 字節(jié),所以長(zhǎng)度為
? ? 10的數(shù)組在內(nèi)存中所占的字節(jié)數(shù)就是40。而總的字節(jié)數(shù)
? ? 除以一個(gè)元素所占的字節(jié)數(shù)就是數(shù)組的長(zhǎng)度 */
? ??
? ? arg = totalgrade/length;
? ? printf("平均分為%d\n",arg);
}
//考試成績(jī)降序排序
void downGrade(int score[10])
{
? ? int i,j;
? ? for(i=9; i>=0; i--)
? ? {
? ? ? ? for(j=0;j<i;j++)
? ? ? ? {
? ? ? ? ? ? if(score[j]<score[j+1])
? ? ? ? ? ? {
? ? ? ? ? ? int temp;
? ? ? ? ? ? temp = score[j];
? ? ? ? ? ? score[j] = score[j+1];
? ? ? ? ? ? score[j+1] = temp;
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? for(i=0;i<10;i++)
? ? {
? ? ?printf("倒序?yàn)?d\n",score[i]);
? ? }
? ??
}
int main()
{
? ? int score[]={67,75,98,63,82,79,81,91,66,84};
? ? printf("十個(gè)考生的總分為:%d\n", totalGrade(score));
? ? highGrade(score);
? ? lowGrade(score);
? ? downGrade(score);
? ? int length = sizeof(score) / sizeof(score[0]);?
? ? /*求數(shù)組長(zhǎng)度 score2[10] = {0,1}? int length = sizeof(score2) / sizeof(score2[0])也等于10*/
? ? int score2[10] = {0,1};? int cut = sizeof(score2) / sizeof(score2[0]);
? ? printf("score的數(shù)組長(zhǎng)度為%d\n", cut);
? ? argGrade(score, length);
? ? return 0;
}
2019-12-06
最后測(cè)試score2的打印 printf內(nèi)容寫(xiě)錯(cuò)了 應(yīng)該是
printf("score2的數(shù)組長(zhǎng)度為%d\n", cut);