1. 程式人生 > >C Primer Plus 第八章 課後答案

C Primer Plus 第八章 課後答案

目錄

複習題

{

}

程式設計練習

a

複習題

1.putchar(getchar())是一個有效表示式,它實現什麼功能?getchar(putchar())是否也是有效表示式

  1. 實現輸出顯示快取區的下一個字元
  2. 不是

2.下面的語句分別完成什麼任務?

a.putchar('H');

b.putchar('\007');

c.putchar('\n');

d.putchar('\b');

a. 列印字元 H

b. 如果系統使用ASDII,發出一聲警報

c. 把游標移動到下一行

d. 把游標後退一格

3.假設有一個名為 count 的可執行程式,用於統計輸入的字元數。設計一個使用 count 程式統計essay檔案中字元數的命令列,並把統計結果儲存在essayct檔案中

count < essay > essayct     or     count > essayct < essay

4.給定複習題3中的程式和檔案,下面哪一條是有效的命令?

a.essayct <essay

b.count essay

c.essay >count

都不是

5.EOF是什麼

由getchar() or scanf() 返回的特殊的值,表明函式檢測到檔案的結尾

6.對於給定的輸出(ch是int型別,而且是緩衝輸入),下面各程式段的輸出分別是什麼?

a.輸入如下:

If you quit, I will.[enter]

程式段如下:

while ((ch = getchar()) != 'i')

        putchar(ch);

b.輸入如下:

Harhar[enter]

程式段如下:

while ((ch = getchar()) != '\n')

{

        putchar(ch++);

        putchar(++ch);

}

a. If you qu

b.HJacrthjacrt

7.C如何處理不同計算機系統中的不同檔案和換行約定

C的標準I/O庫會把不同的檔案對映成統一的流來處理

8.在使用緩衝輸入的系統中,把數值和字元混合輸入會遇到什麼潛在的問題

數字會跳過空格和換行符,但是字元輸入不會:

輸入數字的時候,空格和換行符還會留在快取區,輸入字元的時候會讀取。

【在輸入數字之後要處理空格和換行符】

程式設計練習

1.設計一個程式,統計在讀到檔案結尾之前讀取的字元數

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

int main(void)
{
    FILE* in;
    in = fopen("123.txt", "r");
    char ch;
    long n = 0;
    while((ch = getc(in)) != EOF)
    {
        n++;
    }
    fclose(in);
    printf("%ld\n", n);
    return 0;
}

2.編寫一個程式,在遇到 EOF 之前,把輸入作為字元流讀取。程式要列印每個輸入的字元及其相應的ASCII十進位制值。

注意,在ASCII序列中,空格字元前面的字元都是非列印字元,要特殊處理這些字元。如果非列印字元是換行符或製表符,則分別列印\n或\t。否則,使用控制字元表示法。例如,ASCII的1是Ctrl+A,可顯示為^A。注意,A的ASCII值是Ctrl+A的值加上64。其他非列印字元也有類似的關係。除每次遇到換行符列印新的一行之外,每行列印10對值。

(注意:不同的作業系統其控制字元可能不同。)

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

int main(void)
{
    FILE* in;
    in = fopen("123.txt", "r");
    char ch;
    int n = 0;
    while((ch = getc(in)) != EOF)
    {
        if(ch == '\n')
        {
            putchar('\\');
            putchar('n');
            printf("%d\n", ch);
            n = 0;
        }
        else if(ch == '\t')
        {
            putchar('\\');
            putchar('t');
            printf("%d  ", ch);
        }
        else if(ch < ' ')
        {
            putchar('^');
            putchar(ch + 64);
            printf("%d  ", ch);
        }
        else
        {
            putchar(ch);
            printf("%d  ", ch);
        }
        if(++n % 10 == 0)
        {
            n = 0;
            putchar('\n');
        }
    }
    fclose(in);
    return 0;
}

3.編寫一個程式,在遇到 EOF 之前,把輸入作為字元流讀取。該程式要報告輸入中的大寫字母和小寫字母的個數。假設大小寫字母數值是連續的。或者使用ctype.h庫中合適的分類函式更方便

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

int main(void)
{
    FILE* in;
    in = fopen("123.txt", "r");
    char ch;
    int dn = 0, un = 0;
    while((ch = getc(in)) != EOF)
    {
        if(isupper(ch))
        {
            un++;
        }
        else if(islower(ch))
        {
            dn++;
        }
    }
    printf("%d %d\n", un, dn);
    fclose(in);
    return 0;
}

4.編寫一個程式,在遇到EOF之前,把輸入作為字元流讀取。該程式要報告平均每個單詞的字母數。不要把空白統計為單詞的字母。實際上,標點符號也不應該統計,但是現在暫時不同考慮這麼多(如果你比較在意這點,考慮使用ctype.h系列中的ispunct()函式)

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

int main(void)
{
    FILE* in;
    in = fopen("123.txt", "r");
    char ch;
    int sum = 0, sn = 0, f = 0;
    while((ch = getc(in)) != EOF)
    {
        if(isupper(ch) || islower(ch))
        {
            f = 1;
            sum++;
        }
        else if(f)
        {
            sn++;
            f = 0;
        }
    }
    double average = double(sum) / double(sn);
    printf("%.2lf\n", average);
    fclose(in);
    return 0;
}

5.修改程式清單8.4的猜數字程式,使用更智慧的猜測策略。例如,程式最初猜50,詢問使用者是猜大了、猜小了還是猜對了。如果猜小了,那麼下一次猜測的值應是50和100中值,也就是75。如果這次猜大了,那麼下一次猜測的值應是50和75的中值,等等。使用二分查詢(binary search)策略,如果使用者沒有欺騙程式,那麼程式很快就會猜到正確的答案

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

int main(void)
{
    char response;
    int u = 100, l = 1;
    int guess = 50;
    printf("Pick an integer from 1 to 100. I will try to guess ");
    printf("it.\nRespond with a y if my guess is right and with");
    printf("\nan n if it is wrong.\n");
    printf("Uh...is your number %d?\n", guess);
    while ((response = getchar()) != 'y') /* 獲取響應 */
    {
        while (getchar() != '\n')
        {
            continue; /* 跳過剩餘的輸入行 */
        }
        if (response == 'u')
        {
            u = guess;
            printf("Well, then, is it %d?\n", guess = (guess + l) / 2);
        }
        else if(response == 'l')
        {
            l = guess;
            printf("Well, then, is it %d?\n", guess = (guess + u) / 2);
        }
        else
        {
            printf("Sorry, I understand only u, l or y.\n");
        }
    }
    printf("I knew I could do it!\n");
    return 0;
}

6.修改程式清單8.8中的get_first()函式,讓該函式返回讀取的第1個非空白字元,並在一個簡單的程式中測試

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

char get_first(FILE* in)
{
    char ch;
    while ((ch = getc(in)) <= ' ')
        continue;
    return ch;
}

int main(void)
{
    FILE* in;
    char ch;
    in = fopen("123.txt", "r");
    ch = get_first(in);
    printf("%c\n", ch);
    fclose(in);
    return 0;
}

7.修改第7章的程式設計練習8,用字元代替數字標記選單的選項。用q代替5作為結束輸入的標記

#include <stdio.h>
#include <stdlib.h>
#define MAXT 40.0
#define GH 10.0
#define FR 300.0
#define SR 450.0
#define FTR 0.15
#define STR 0.20
#define TTR 0.25



int main(void)
{
    float t, sum, tax, gain;
    scanf("%f", &t);
    getchar();
    if(t > MAXT)
    {
        t = MAXT + (t - MAXT) * 1.5;
    }
    float gh;
    int f = 0, x = 1;
    char num;
    printf("***************************************************************** \n");
    printf("Enter the number corresponding to the desired pay rate or action: \n");
    printf("a) $8.75/hr           b) $9.33/hr\nc) $10.00/hr          d) $11.20/hr\nq) quit \n");
    printf("***************************************************************** \n");
    num = getchar();//要在上一個輸入之後加上getchar()處理回車
    getchar();
    while(x)
    {
        switch(num)
        {
            case 'a':
                gh = 8.75;
                x = 0;
                break;
            case 'b':
                gh = 9.33;
                x = 0;
                break;
            case 'c':
                gh = 10.00;
                x = 0;
                break;
            case 'd':
                gh = 11.20;
                x = 0;
                break;
            case 'q':
                return 0;
                break;
            default:
                printf("input a, b, c, d or q:");
                num = getchar();
                getchar();
        }
    }
    sum = gh * t;
    if(sum <= FR)
    {
        tax = sum * FTR;
        gain = sum - tax;
    }
    else if(sum > FR && sum < SR)
    {
        tax = FR * FTR + (sum - FR) * STR;
        gain = sum - tax;
    }
    else if(sum > SR)
    {
        tax = FR * FTR + (SR - FR) * STR + (sum - SR) * TTR;
        gain = sum - tax;
    }
    printf("%-10.2f%-10.2f%-10.2f%-10.2f\n", t, sum, gain, tax);
    return 0;
}

8.編寫一個程式,顯示一個提供加法、減法、乘法、除法的選單。獲得使用者選擇的選項後,程式提示使用者輸入兩個數字,然後執行使用者剛才選擇的操作。該程式只接受選單提供的選項。程式使用float型別的變數儲存使用者輸入的數字,如果使用者輸入失敗,則允許再次輸入。進行除法運算時,如果使用者輸入0作為第2個數(除數),程式應提示使用者重新輸入一個新值。

該程式的一個執行示例如下:

Enter the operation of your choice:

a. add                s. subtract

m. multiply       d. divide

q. quit

a

Enter first number: 22 .4

Enter second number: one

one is not a number.

Please enter a number, such as 2.5, -1.78E8, or 3: 1

22.4 + 1 = 23.4

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

int checkinput()
{
    char mc;
    float n;
    while(scanf("%f", &n) != 1)
    {
        while((mc = getchar()) > ' ')
        {
            putchar(mc);
        }
        while((mc = getchar()) <= ' ')
            continue;
        printf(" is not a number\n");
        printf("Please enter a number, such as 2.5, -1.78E8, or 3:");
    }
    return n;
}

int main(void)
{
    char ch;
    int x = 1;
    printf("Enter the operation of your choice: \na. add            s. subtract\nm. multiply       d. divide \nq. quit\n");
    while(x)
    {
        ch = getchar();
        getchar();
        if(ch != 'a' && ch != 's' && ch != 'm' && ch != 'd' && ch != 'q')
        {
            printf("input a ,s, m, d or q:");
            continue;
        }
        else if(ch == 'q')
        {
            return 0;
        }
        else
        {
            x = 0;
        }
    }
    float fn, sn;
    printf("Enter first number:");
    fn = checkinput();
    printf("Enter second number:");
    sn = checkinput();
    if(ch == 'd')
    {
        while(sn == 0)
        {
            printf("The second number can't be 0,input it again:");
            sn = checkinput();
        }
    }
    switch(ch)
    {
        case 'a':
            printf("%.2f + %.2f = %.2f", fn, sn, fn + sn);
            break;
        case 's':
            printf("%.2f - %.2f = %.2f", fn, sn, fn - sn);
            break;
        case 'm':
            printf("%.2f * %.2f = %.2f", fn, sn, fn * sn);
            break;
        case 'd':
            printf("%.2f / %.2f = %.2f", fn, sn, fn / sn);
            break;
        default:
            break;
    }
    return 0;
}