103年地方特考四等程式設計概要

二、請回答下列 C 語言程式問題:

()請問下列函式,f1(0.5, 6.5) 的輸出為何 (該數字的精確度到小數點後第一位)?(5分)

double f1(double x, double y) {

int a = 2, b = 1, c = 1;

x += (a+b+c == 2*b);

x -= a*b/x;

return (x+c);

}

()請問下列函式,f2(0, 3) 的輸出為何?(5分)

int f2(int x, int y) {

if (x > 5) return (y+1);

else if (x > 3) return 3+f2(x+1, y+1);

else return 1+f2(x+1, y);

}

()以下程式功能為:輸入的第一個參數為指定的進位制 (base)B(2 <=B<=9),第二個參數為以 B 進位制表示的數字,N(0 < N < 10,000)。請將 N 經十進位制轉換後輸出,例如將九進位的1621轉成十進位的1234,我們有程式碼,如 printf("d\n", transformX10(9, 1621));其中會呼叫 transformX10(9, 1621) 做進位制 (base) 的轉換且其輸出為1234。有關 transformX10 的程式如下,請填寫空格處。(每一空格5分,共15分)

int transformX10(int base, int x) {

int ans = 0, index = 1;

while (x >   (1)  )

ans =   (2)   +index*(x%10);

index =   (3)   *base;

x = x/10;

}

return ans;

}

答:

()

#include <stdio.h>

double f1(double x, double y) {

    int a = 2, b = 1, c = 1;

    x += (a + b + c == 2 * b);

    x -= a * b / x;

    return (x + c);

}

int main( ) {

    printf("%.1f", f1(0.5, 6.5));

    return 0;

}

執行結果

-2.5

說明:

(a + b + c == 2 * b); => 2+1+1 == 2×1 => 0

x += (a + b + c == 2 * b); => x += 0 => x = 0.5

x -= a * b / x; => x -= 2×1 / 0.5; => x = 0.5-4 = -3.5

return (x + c); => -3.5+1 = -2.5

()

#include <stdio.h>

int f2(int x, int y) {

    if (x > 5) return (y + 1);

    else if (x > 3) return 3 + f2(x + 1, y + 1);

    else return 1 + f2(x + 1, y);

}

int main( ) {

    printf("%d", f2(0, 3));

    return 0;

}

執行結果

16

說明:

f2(0, 3) = 1+f2(0+1, 3) => 1+f2(1, 3)

f2(1, 3) = 1+f2(1+1, 3) => 1+f2(2, 3)

f2(2, 3) = 1+f2(2+1, 3) => 1+f2(3, 3)

f2(3, 3) = 1+f2(3+1, 3) => 1+f2(4, 3)

f2(4, 3) = 3+f2(4+1, 3+1) => 3+f2(5, 4)

f2(5, 4) = 3+f2(5+1, 4+1) => 3+f2(6, 5)

f2(6, 5) = return (5+1) = return 6

f2(5, 4) = 3+f2(6, 5) = 3+6 = 9

f2(4, 3) = 3+f2(5, 4) = 3+9 = 12

f2(3, 3) = 1+f2(4, 3) = 1+12 = 13

f2(2, 3) = 1+f2(3, 3) = 1+13 = 14

f2(1, 3) = 1+f2(2, 3) = 1+14 = 15

f2(0, 3) = 1+f2(1, 3) = 1+15 = 16

()

#include <stdio.h>

int transformX10(int base, int x) {

    int ans = 0, index = 1;

    while (x > 0) { // (1) 空格處填0

        ans = ans + index * (x % 10); // (2) 空格處填 ans

        index = index * base; // (3) 空格處填 index

        x = x / 10;

    }

    return ans;

}

int main( ) {

    printf("%d", transformX10(9, 1621));

    return 0;

}

執行結果

1234

arrow
arrow
    文章標籤
    地方特考四等程式設計概要
    全站熱搜

    jacksaleok 發表在 痞客邦 留言(0) 人氣()