111年高考三級程式設計
一、請問以下三小題 C 程式執行的結果為何?請注意須說明答案是如何產生的,否則不給分。 (一)(5分) #include <stdio.h> #include <stdlib.h> int main(void) { int x; float y; for (x = 0, y = 50; x < 25; x += 5, y /= 2) printf("x = %d, y = %4.2f\n", x, y); return 0; } (二)(5分) #include <stdio.h> #include <stdlib.h> int a = 10, fun(int); int main(void) { int b = 6; printf("a = %d, b = %d, fun(a) = %d\n", a, b, fun(a)); return 0; } int fun(int b) { a -= 5; b /= 2; return(a+b); } (三)(10分) #include <stdio.h> #include <stdlib.h> #define SIZE 10 void fun(int *, int); int main(void) { int x[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; fun(x, SIZE); printf("\n"); return 0; } void fun(int *a, int size) { if (size > 0) { fun(a+3, size-3); printf("*(a+%d) = %d\n", SIZE-size, *a); } } |
答:
(一)
#include <stdio.h> #include <stdlib.h> int main(void) { int x; float y; for (x = 0, y = 50; x < 25; x += 5, y /= 2) printf("x = %d, y = %4.2f\n", x, y); return 0; } |
執行結果:
x = 0, y = 50.00
x = 5, y = 25.00
x = 10, y = 12.50
x = 15, y = 6.25
x = 20, y = 3.12
說明:
回合數 |
x |
y |
x < 25 |
x+ = 5 |
y/ = 2 |
printf(…) |
第1回 |
0 |
50 |
0 < 25 |
5 |
25 |
x = 0, y = 50.00 |
第2回 |
5 |
25 |
5 < 25 |
10 |
12.5 |
x = 5, y = 25.00 |
第3回 |
10 |
12.5 |
10 < 25 |
15 |
6.25 |
x = 10, y = 12.50 |
第4回 |
15 |
6.25 |
15 < 25 |
20 |
3.125 |
x = 15, y = 6.25 |
第5回 |
20 |
3.125 |
20 < 25 |
25 |
1.5625 |
x = 20, y = 3.12 |
第6回 |
25 |
1.5625 |
25 ≠ 25 |
- |
- |
- |
(二)
#include <stdio.h> #include <stdlib.h> int a = 10, fun(int); int main(void) { int b = 6; printf("a = %d, b = %d, fun(a) = %d\n", a, b, fun(a)); return 0; } int fun(int b) { a -= 5; b /= 2; return(a+b); } |
執行結果:
a = 5, b = 6, fun(a) = 10
說明:
int main(void):
回合數 |
a |
b |
printf(…) |
第1回 |
10 |
6 |
a = 10, b = 6, fun(a) = fun(10) |
第2回 |
10 |
6 |
a = 5, b = 6, fun(a) = 10 |
int fun(int b):
回合數 |
a |
b |
fun(int b) |
a -= 5 |
b /= 2 |
return(a+b) |
第1回 |
10 |
10 |
fun(10) |
A = a-5 = 10-5 = 5 |
b = 10/2 = 5 |
return(5+5) = return(10) |
(三)
#include <stdio.h> #include <stdlib.h> #define SIZE 10 void fun(int *, int); int main(void) { int x[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; fun(x, SIZE); printf("\n"); return 0; } void fun(int *a, int size) { if (size > 0) { fun(a+3, size-3); printf("*(a+%d) = %d\n", SIZE-size, *a); } } |
執行結果:
*(a+9) = 10
*(a+6) = 7
*(a+3) = 4
*(a+0) = 1
說明:
void fun(int *a, int size):
回合數 |
SIZE |
size |
size > 0 |
fun(a+3, size-3) |
SIZE-size |
*a |
a+%d |
printf(…) |
第1回 |
10 |
10 |
10 > 0 |
fun(a+3, 10-3) = fun(a+3, 7) |
10-10 = 0 |
1 |
a+0 |
*(a+0) = 1 |
第2回 |
10 |
7 |
7 > 0 |
fun(a+3, 7-3) = fun(a+3, 4) |
10-7 = 3 |
4 |
a+3 |
*(a+3) = 4 |
第3回 |
10 |
4 |
4 > 0 |
fun(a+3, 4-3) = fun(a+3, 1) |
10-4 = 6 |
7 |
a+6 |
*(a+6) = 7 |
第4回 |
10 |
1 |
1 > 0 |
fun(a+3, 1-3) = fun(a+3, -2) |
10-1 = 9 |
10 |
a+9 |
*(a+9) = 10 |
第5回 |
10 |
-2 |
-2 < 0 |
- |
- |
- |
- |
- |