C Primer Plus (第六版)中文版 第七章 编程练习答案

1、编写一个程序读取输入,读到#字符停止,然后报告读取空格数,换行符数目以及所有的其它字符数目。

#include<stdio.h>

int main()
{
    int sp_ct = 0, nl_ct = 0, other = 0;
    char ch;
    printf("Enter a sentence: \n");

    while((ch = getchar()) != '#')
    {
        if(ch == ' ')
            sp_ct++;
        else if(ch == '\n')
            nl_ct++;
        else
            other++;
    }
    printf("spaces: %d, newlines: %d, others: %d\n", sp_ct, nl_ct, other);
    return 0;
}

2.编写一个程序读取输入,读到#字符停止。程序要打印每个输入的字符以及对应的ASCII码(十进制)。一行打印8个字符。建议:使用字符计数和求模运算符(%)在每8个循环周期时打印一个换行符。

#include<stdio.h>
int main()
{
    char ch;
    const int LINE = 8; 
    int chsum = 0;
    printf("Enter a sentence: \n");
    while((ch = getchar()) != '#')
    {
        printf("%c: %d\t",ch,ch);  
        chsum++;  
       if(chsum % LINE == 0)  
           printf("\n");  
    }

        printf("\n"); 
    return 0;
}

3.编写一个程序,读取整数,直到用户输入0。输入结束后,程序应该报告输入的偶数(不包括0)个数、这些偶数的平均值,输入的奇数个数以及奇数的平均值。

#include<stdio.h>

int main()
{
    int n, even_num = 0, odd_num = 0;
    double even_aver = 0.0, odd_aver = 0.0;
    int even_sum = 0, odd_sum = 0;

    printf("Enter integers; ");
    printf("Enter 0 to quit.\n");
    while((scanf("%d", &n) == 1) && (n != 0))
    {
        if(n % 2 == 0)
        {
            even_num++;
            even_sum += n;
        }
        else
        {
            odd_num++;
            odd_sum += n;
        }
    }

    printf("even_num: %d", even_num);
    if(even_num > 0)
    {
        even_aver = even_sum/even_num;
        printf(" even_aver: %.2f", even_aver);
    }
    printf("\n");

    printf("odd_num: %d", odd_num);
    if(odd_num > 0)
    {
        odd_aver = odd_sum/odd_num;
        printf(" odd_aver: %.2f", odd_aver);
    }
    printf("\n");
    printf("Done!\n");
    return 0;
}

4.使用if else语句编写一个程序读取输入,读到#停止。用感叹号代替句号,用两个感叹号代替原来的感叹号,最后报告进行了多少次替代。

#include<stdio.h>
int main()
{
    char ch;
    int i = 0,j = 0;

    while((ch = getchar()) != '#')
    {
        if(ch == '.')
        {
            putchar('!');
            i++;
        }
        else if(ch == '!')
        {
            putchar('!');
            putchar('!');
            j++;
        }
        else
            putchar(ch);
    }

    printf("\nthe times of '.' replaced is: %d\n", i);
    printf("the times of '!' replaced is: %d\n", j);
    return 0;
}

5.用switch重写练习4。

#include<stdio.h>
int main()
{
    char ch;
    int i = 0,j = 0;

    while((ch = getchar()) != '#')
    {
        switch(ch)
        {
        case '.':
            putchar('!');
            i++;
            break;
        case '!':
            putchar('!');
            putchar('!');
            j++;
            break;
        default:
            putchar(ch);
        }
    }

    printf("\nthe times of '.' replaced is: %d\n", i);
    printf("the times of '!' replaced is: %d\n", j);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Tanyongyin/article/details/78671645