You are on page 1of 5

計算機概論第八週 主要內容:陣列

範例一:可連續輸入座號、國文、英文、數學分數,計算總分及平均,列印成績單。
Step 1: 先完成單筆資料輸入

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int no,sub1,sub2,sub3;
printf("請依序輸入座號及國文、英文、數學的分數(請以逗點圈隔):");
scanf("%d,%d,%d,%d",&no,&sub1,&sub2,&sub3);
printf("座號\t國文\t英文\t數學\n");
printf("%3d\t%3d\t%3d\t%3d\n",no,sub1,sub2,sub3);
system("pause");
return 0;
}
Step 2: 再用while迴圈改成可連續多筆資料輸入,按任意鍵可繼續輸入,按Ctrl+q結束

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int no,sub1,sub2,sub3;
char ch=‘1’; // 按鍵接收變數的初始值任意設定,非17即可
while(ch!=17)
{
printf("請依序輸入座號及國文、英文、數學的分數(請以逗點圈隔):");
scanf("%d,%d,%d,%d",&no,&sub1,&sub2,&sub3);
printf("座號\t國文\t英文\t數學\n");
printf("%3d\t%3d\t%3d\t%3d\n",no,sub1,sub2,sub3);
printf("按任意鍵繼續輸入,按Ctrl+q結束。\n");
ch=getch(); // 等待接收按鍵,參閱課本4-33頁說明
}
system("pause");
return 0;
}
Step 3: 使用陣列,完成多筆資料輸入,再列印成績單

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int no[20],sub1[20],sub2[20],sub3[20],k=0,i;
char ch='1';
while(ch!=17)
{
printf("請依序輸入座號及國文、英文、數學的分數(請以逗點圈隔):");
scanf("%d,%d,%d,%d",&no[k],&sub1[k],&sub2[k],&sub3[k]);
k++;
printf("按任意鍵繼續輸入,按Ctrl+q結束。\n");
ch=getch();
}
printf("座號\t國文\t英文\t數學\n");
for(i=0;i<k;i++)
printf("%3d\t%3d\t%3d\t%3d\n",no[i],sub1[i],sub2[i],sub3[i]);
system("pause");
return 0;
}
Step 4: 計算總分及平均,再列印完整成績單

#include <stdio.h>
#include <stdlib.h>
#define std_no 20 // 定義常數
int main(void)
{
int no[std_no],sub1[std_no],sub2[std_no],sub3[std_no],sum[std_no]={0},k=0,i;
float ave[std_no];
char ch='1';
while(ch!=17)
{
printf("請依序輸入座號及國文、英文、數學的分數(請以逗點圈隔):");
scanf("%d,%d,%d,%d",&no[k],&sub1[k],&sub2[k],&sub3[k]);
sum[k]=sub1[k]+sub2[k]+sub3[k]; // 計算總分
ave[k]=(float)sum[k]/3; // 計算平均
k++;
printf("按任意鍵繼續輸入,按Ctrl+q結束。\n");
ch=getch();
}
printf("座號\t國文\t英文\t數學\t總分\t平均\n");
for(i=0;i<k;i++)
printf("%3d\t%3d\t%3d\t%3d\t%3d\t%5.2f\n",no[i],sub1[i],sub2[i],sub3[i],sum[i],ave[i]);
system("pause");
return 0;
}
Step 5: 最後改成用二維陣列記錄每一位學生的所有資料

#include <stdio.h>
#include <stdlib.h>
#define std_no 20 // 定義常數(學生人數)
#define sub_no 6 // 定義常數(欄位數量)
int main(void)
{
float no[std_no][sub_no];
int k=0,i,j;
char ch='1';
while(ch!=17)
{
printf("請依序輸入座號及國文、英文、數學的分數(請以逗點圈隔):");
scanf("%f,%f,%f,%f",&no[k][0],&no[k][1],&no[k][2],&no[k][3]);
no[k][4]=no[k][1]+no[k][2]+no[k][3];
no[k][5]=no[k][4]/3;
k++;
printf("按任意鍵繼續輸入,按Ctrl+q結束。\n");
ch=getch();
}
printf("座號\t國文\t英文\t數學\t總分\t平均\n");
for(i=0;i<k;i++)
{
for(j=0;j<sub_no-1;j++)
printf("%3.0f\t",no[i][j]);
printf("%5.2f\n",no[i][sub_no-1]);
}
system("pause");
return 0;
}

You might also like