# TQC+ 302 ``` 302 函式與陣列 請撰寫一程式,包含名為compute()的函式,接收主程式傳遞的一個期中考分數,compute()判斷分數值,若分數在0~100以外,則回傳「-1」;若分數大於等於60,則加5分;否則一律加10分,回傳至主程式輸出。 輸入說明 一個整數 輸出說明 調整後的分數 範例輸入1 78 範例輸出1 83 範例輸入2 120 範例輸出2 -1 #include <stdio.h> int compute(int); int main(){ int s; scanf("%d", &s); printf("%d", compute(s) ); } int compute(int a) { if (a>=60 && a<=100){ return a+5; } else if (a>=0 && a<60){ return a+10; } else {return -1;} } 304 請撰寫一程式,包含名為compute()的函式,接收主程式傳遞的一個陣列,陣列中有六個整數,compute()判斷陣列中有幾個3的倍數並回傳至主程式輸出。 輸入說明 六個整數 輸出說明 有幾個3的倍數 範例輸入 10 20 30 40 50 60 範例輸出 2 #include <stdio.h> int compute(int a[]); int main(){ int n[6]; for (int i=0; i<6; ++i){ scanf("%d", &n[i]); } printf("%d", compute(n) ); } int compute(int a[]) { int b=0; for (int i=0; i<6; ++i){ if (a[i] % 3 == 0){ ++b; } } return b; } 306 請撰寫一程式,包含名為compute()的函式,接收主程式傳遞的一個整數n(n ≥ 0),compute()計算n階乘值後回傳至主程式,並輸出n階層結果。 階乘的定義如下: 輸入說明 一個整數n(n ≥ 0) 輸出說明 n階層值 範例輸入 7 範例輸出 7!=5040 #include <stdio.h> int compute(int); int main(){ int n; scanf("%d", &n); printf("%d!=%d", n, compute(n) ); } int compute(int a) { if (a==0 || a==1){ return 1; } else { int b=1; for (int i=2; i<=a; ++i){ b*=i; } return b; } } 308 請撰寫一程式,包含名為compute()的函式,接收主程式傳遞的一個正整數n(n<10),compute()計算費式數列第n項的值後回傳至主程式,並輸出倒印費氏數列。 提示:費氏數列的某一項數字是其前兩項的和,而且第0項為0,第一項為1,表示方式如下: 輸入說明 一個小於10的正整數 輸出說明 倒印費氏數列 #include <stdio.h> int compute(int a); int main(){ int n; scanf("%d", &n); for (int i=n; i>=1; --i){ printf("fib(%d)=%d\n", i, compute(i) ); } } int compute(int a) { if (a==1 || a==2){ return 1; } else if (a>2){ int b=1, c=1, d; for (int i=2; i<a; ++i){ d=b+c; b=c; c=d; } return d; } } //這想了一段時間 XD https://dywang.csie.cyut.edu.tw/dywang/clanguage/node145.html #include <stdio.h> int *compute(int); int main(){ int n; scanf("%d", &n); int *y1; y1= compute(n); for (int i=n; i>=1; --i){ printf("fib(%d)=%d\n", i, *(y1+i-1) ); } } int *compute(int a) { static int x[9]={1,1}; if (a>2){ for (int i=2; i<a; ++i){ x[i]=x[i-1]+x[i-2]; } } return x; } 310 請撰寫一程式,包含名為compute()的函式,接收主程式傳遞的一個整數n(0 < n < 1000),compute()輸出所有小於n的阿姆斯壯數並回傳總和至主程式輸出。 阿姆斯壯數的定義:若為k位數的正整數,則其所有位數數字的k次方與該數相等。 輸入說明 一個整數n(0 < n < 1000) 輸出說明 所有小於n的阿姆斯壯數與其總和 範例輸入 999 範例輸出 1 2 3 4 5 6 7 8 9 153 370 371 407 1346 #include <stdio.h> #include <math.h> int compute(int); int digits(int); int main(){ int n; scanf("%d", &n); printf("%d", compute(n) ); } //Calculate the Armstrong number int compute(int a) { int total = 0; for (int i=1; i<a; ++i){ if (a<=10){ printf("%d\n", i); total += i; } else { int count = 0; int j = i; int k = digits(j); while(j != 0) { count += pow(j % 10, k); j /= 10; } if (i == count){ printf("%d\n", count); total += i; } } } return total; } //Calculate how many digits the number n has int digits(int n) { int count = 0; while(n != 0) { n /= 10; ++count; } return count; } ```