# C言語復習勉強会:初級編-1 ## 問1:for文で繰り返し n個の科目数とそれぞれのテストの点数を入力すると、平均点(小数点第1位まで)が求まるプログラムを作成せよ。 ### 入力例 ``` 科目数を入力:4 科目0の点数:56 科目1の点数:67 科目2の点数:78 科目3の点数:89 ``` ### 期待する結果 ``` 平均72.5点 ``` --- ### C言語の文法 ##### for文の書き方 <details><summary>表示</summary> ``` ``` </details> ##### 値を合計する <details><summary>表示</summary> 加算代入演算子:"+="が使える。 ``` ``` </details> ##### 小数点の表示 <details><summary>表示</summary> ``` ``` </details> ##### 割り算 <details><summary>表示</summary> ``` ``` </details> --- ### ロジック(わからない場合) <details><summary>表示</summary> ```cpp= #include<stdio.h> int main(void) { 整数型 n, score; 浮動小数点数型 sum; "科目数を入力:"を出力; 変数nにキーボードから数字を入力; sum に 0; for (整数型 i に 1; nはiより大きい; i++){ "科目 変数i の点数:"を出力; 変数scoreにキーボードから数字を入力; sum += score; } sum/nを出力; // 平均値 return 0; } ``` </details> --- ### 答え(最後に見る) <details><summary>表示</summary> ```cpp= #include<stdio.h> int main(void) { int n, score; double sum; printf("科目数を入力:"); scanf("%d", &n); sum = 0; for (int i = 0; i < n; i++){ printf("科目%dの点数:", i); scanf("%d", &score); sum += score; } printf("平均%.1f点\n", sum / n); return 0; } ``` </details> ## 問2:if文で条件分岐 n個の科目数、テストの点数、その科目の単位数をキーボードから入力するとGPA(成績評価点平均)が求まるプログラムを作成せよ。 ただし、GPAは、小数点第3位まで出力する。 GPAの基準: ``` 90点以上の場合 評価点 は 4 80点以上の場合 評価点 は 3 70点以上の場合 評価点 は 2 60点以上の場合 評価点 は 1 その他 評価点 は 0 ``` GPAは、下記の式で求めます。 $$ 加重和 = 評価点 \times 単位数\\ GPA = 加重和 / 総単位数 $$ ### 期待する結果 ``` 科目数を入力:2 科目1の点数:67 科目1の単位数:2 科目2の点数:89 科目2の単位数:1 GPA:1.667 ``` --- ##### if文の書き方 <details><summary>表示</summary> ``` ``` </details> ##### 値を合計する書き方 <details><summary>表示</summary> ``` ``` </details> ##### 小数点の表示 <details><summary>表示</summary> ``` ``` </details> --- ### ロジック(わからない場合) <details><summary>表示</summary> ```cpp= #include<stdio.h> int main(void) { int n, score, gp, cred; int credits; double wgps; printf("科目数を入力:"); scanf("%d", &n); wgps = 0; credits = 0; for (int i = 0; i < n; i++) { printf("科目%dの点数:", i); scanf("%d", &score); if (score >= 90) gp = 4; else if (score >= 80) gp = 3; else if (score >= 70) gp = 2; else if (score >= 60) gp = 1; else gp = 0; printf("科目%dの単位数:", i); scanf("%d", &cred); credits += cred; wgps += gp*cred; } printf("GPA:%.3f\n", wgps / credits); return 0; } ``` </details> --- ### 答え(最後に見る) <details><summary>表示</summary> ```cpp= #include<stdio.h> int main(void) { int n, score, gp, cred; int credits; double wgps; printf("科目数を入力:"); scanf("%d", &n); wgps = 0; credits = 0; for (int i = 0; i < n; i++) { printf("科目%dの点数:", i); scanf("%d", &score); if (score >= 90) gp = 4; else if (score >= 80) gp = 3; else if (score >= 70) gp = 2; else if (score >= 60) gp = 1; else gp = 0; printf("科目%dの単位数:", i); scanf("%d", &cred); credits += cred; wgps += gp*cred; } printf("GPA:%.3f\n", wgps / credits); return 0; } ``` </details>