C primer plus(第五版)编程练习第七章

来源:互联网 发布:如何参观清华大学知乎 编辑:程序博客网 时间:2024/04/18 18:50
第一题:编写一个程序,该程序读取输入直到遇到#字符,然后报告读取的空格数据、读取的换行符数目以及读取的所有其他字符数目。
解:
代码如下:
#include <stdio.h>
int main(void)
{
    int sp = 0;
    int en = 0;
    int ot = 0;
    char ch;

    printf("Input a text:\n");
    while((ch = getchar()) != '#')
    {
        if(ch == '\n')
            en++;
        else if(isblank(ch))
            sp++;
        else
            ot++;
    }
    printf("there are %d spaces,%d enter and %d other characters\n",sp,en,ot);
    return 0;
}
———————————————分割线—————————————————
第二题:编写一个程序,该程序读取输入直到遇到#字符。使程序打印每个输入的字符以及它的十进制ASCII码,每行打印8个字符/编码对。建议:利用字符技术和模运算符(%)在每8个循环周期时打印一个换行符。
解:本题直接获取字符立刻打印的话,会在回车时就输出结果,并可以继续输入,这里采用了先存储,后处理的方法避免这种情况。
代码如下:
#include <stdio.h>
#include <string.h>
int main(void)
{
    int i;
    int n =0;
    char text[1000];

    printf("Input a text:\n");
    while((text[n] = getchar()) != '#')
        n++;
    while(getchar() != '\n')
        continue;
    n =0;
    i = strlen(text);
    while(n < i)
    {
        if(text[n] != '#')
        {
            putchar(text[n]);
            printf("/%d  ",text[n]);
            n++;
            if((n % 8) == 0)
                printf("\n");
        }
        else
            break;
    }
    printf("\n");
    return 0;
}
———————————————分割线—————————————————
第三题:编写一个程序,该程序读取整数,直到输入0.输入终止后,程序应该报告输入的偶数(不含0)总个数,偶数的平均值,输入的奇数综个数以及奇数的平均值。
解:
代码如下:
#include <stdio.h>
int main(void)
{
    int n,i,j,s1,s2,a1,a2;
    i = 0;
    j = 0;
    s1 = 0;
    s2 = 0;

    printf("Input int numbers:\n");
    while(scanf("%d",&n) && n != 0)
    {
        if(n % 2 != 0)
        {
            i++;
            s1 += n;
        }
        else
        {
            j++;
            s2 += n;
        }
    }
    printf("there are %d odd number,average is %d\n",i,s1 / i);
    printf("there are %d even number,average is %d\n",j,s2 / j);
    return 0;
}
———————————————分割线—————————————————
第四题:利用if else语句编写程序读取输入,直到#。用一个感叹号代替每个句号,将原有的每个感叹号用两个感叹号代替,最后报告进行了多少次替代。
解:
代码如下:
#include <stdio.h>
#define P '.'
#define E '!'
#define DE "!!"
int main(void)
{
    char ch;
    int n = 0;
  
    printf("Input a text,end with #:\n");
    while((ch = getchar()) != '#')
    {
        if(ch == P)
        {
            putchar(E);
            n++;
        }
        else if(ch == E)
        {
            printf(DE);
            n++;
        }        
        else
            putchar(ch);
    }
    printf("replace %d times\n",n);
    return 0;
}
———————————————分割线—————————————————
第五题:用switch重做第三题
解:
代码如下:
#include <stdio.h>
int main(void)
{
    int n,i,j,s1,s2,a1,a2;
    i = 0;
    j = 0;
    s1 = 0;
    s2 = 0;

    printf("Input int numbers:\n");
    while(scanf("%d",&n) && n != 0)
    {
        switch(n % 2) 
        {
            case 1:
                        i++;
                        s1 += n;
                        break;
            case 0:
                        j++;
                       s2 += n;
        }
    }
    printf("there are %d odd number,average is %d\n",i,s1 / i);
    printf("there are %d even number,average is %d\n",j,s2 / j);
    return 0;
}
———————————————分割线—————————————————
第六题:编写一个程序读取输入,直到#,并报告序列ei出现的次数。提示:记住前一个字符和当前字符,并用类似"Receive your eieio award"的输入来测试。
解:
代码如下:
#include <stdio.h>
int main(void)
{
    char ch_pre,ch_cur;
    ch_pre = ' ';
    int n = 0;

    printf("Input a text:\n");
    while((ch_cur = getchar()) != '#')
    {
        if(ch_pre == 'e' && ch_cur == 'i')
            n++;
        ch_pre = ch_cur;
    }
    printf(" %d times ei exist \n",n);
    return 0;
}
———————————————分割线—————————————————
第七题:编写程序,要求输入一周中的工作小时数,然后打印工资总额、税金以及净工资。作如下假设:
a,基本工资等级=10.00美元/小时
b,加班(超过40小时)=1.5倍的时间
c,税率 前300美元为15%,下一个150美元为20%,余下的位25%
用#define定义常量,不必关心本例是否符合当前的税法。
解:
代码如下:
#include <stdio.h>
#define H_WAGE 10.00
#define H_OVER 40.0
#define H_RATE 1.5
#define D_1 300.0
#define D_2 450.0
#define T_1 0.15
#define T_2 0.2
#define T_3 0.25
int main(void)
{
    float total,tax,salary,hour;

    printf("Input how many hours you worked last week:");
    scanf("%f",&hour);
    if(hour <= H_OVER)
        total = hour * H_WAGE;
    else
        total = (H_OVER + (hour - H_OVER) * H_RATE) * H_WAGE;
    if(total <= D_1)
        tax = total * T_1;
    else if(total > D_1 && total <= D_2)
        tax = D_1 * T_1 + (D_2 - total) * T_2;
    else
        tax = D_1 * T_1 + (D_2 - D_1) * T_2 + (total - D_2) * T_3;
    salary = total - tax;
    printf("last week you worked %.2f hours,your total salary is %.2f,reduce tax %.2f,you own %.2f\n",hour,total,tax,salary);
    return 0;
}
———————————————分割线—————————————————
第八题:修改第七题的假设a,使程序提供一个可选择工资等级的菜单。用switch选择工资等级。程序运行的开头应该像这样:
**************************************************************************
Enter the number corresponding to the desired pay rate or action:
1) $8.75/hr    2) $9.33/hr
3) $10.00/hr  3) $11.20/hr
5) quit
**************************************************************************
如果选择1到4,那么程序应该请求输入工作小时数。程序应该一直循环运行,直到输入5.如果输入1到5之外的选项,那么程序应该提醒用户核实的选项是哪些,然后再循环。用#define为各种工资等级和税率定义常量。
解:使用两个自定义函数,处理对工资等级的选择问题和计算问题,主函数循环执行这两个自定义函数。
代码如下:
#include <stdio.h>
#define H_WAGE1 8.75
#define H_WAGE2 9.33
#define H_WAGE3 10.00
#define H_WAGE4 11.20
#define QUIT 5.0
#define H_OVER 40.0
#define H_RATE 1.5
#define D_1 300.0
#define D_2 450.0
#define T_1 0.15
#define T_2 0.2
#define T_3 0.25
float chose(void);
void com(float h_wage);
int main(void)
{
    float h_wage;

    while((h_wage = chose()) != QUIT)
        com(h_wage);
    printf("Good Bye!\n");
    return 0;
}
float chose(void)
{
    float h_wage;
    int choice;
 
    do
    {
        printf("**************************************************************************\n");
        printf("Enter the number corresponding to the desired pay rate or action:\n");
        printf("1) $8.75/hr                                            2) $9.33/hr\n");
        printf("3) $10.00/hr                                           4) $11.20/hr\n");
        printf("5) quit\n");
        printf("**************************************************************************\n");
        scanf("%d",&choice);
        while(getchar() != '\n'); //scanf()函数在读取数据时,如果不符合格式则会读取失败,该输入仍然在缓冲区中,如果是循环读取,那么就会造成无限循环。这时就需要清空缓存。
        switch(choice)
        {
            case 1:h_wage = H_WAGE1;
                       break;
            case 2:h_wage = H_WAGE2;
                       break;
            case 3:h_wage = H_WAGE3;
                       break;
            case 4:h_wage = H_WAGE4;
                       break;
            case 5:h_wage = QUIT;
                       break;
            default:printf("bad choice,try again\n");
        }
    }while(choice < 1 || choice > 5);
    return h_wage;
}
void com(float h_wage)
{
    float hour,total,tax,salary;

    printf("Input how many hours you worked last week:");
    scanf("%f",&hour);
    while(getchar() != '\n');
    if(hour <= H_OVER)
        total = hour * h_wage;
    else
        total = (H_OVER + (hour - H_OVER) * H_RATE) * h_wage;
    if(total <= D_1)
        tax = total * T_1;
    else if(total > D_1 && total <= D_2)
        tax = D_1 * T_1 + (D_2 - total) * T_2;
    else
        tax = D_1 * T_1 + (D_2 - D_1) * T_2 + (total - D_2) * T_3;
    salary = total - tax;
    printf("last week you worked %.2f hours,your total salary is %.2f,reduce tax %.2f,you own %.2f\n",hour,total,tax,salary);
}
———————————————分割线—————————————————
第九题:编写一个程序,接受一个整数输入,然后显示所有小于或等于该函数的素数。
解:
代码如下:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
    int n,i,j;
    bool isprime;

    printf("Input a int number.\n");
    scanf("%d",&n);
    printf("prime numbers:\n");
    for(i = 2;i <= n;i++)
    {
        for(j = 2,isprime = true;(j * j) <= i;j++)
        {
            if(i % j == 0)
                isprime = false;
        }
        if(isprime)
            printf("   %d",i);
    }
    printf("\n");
    return 0;
}
———————————————分割线—————————————————
第十题:1988年United States Federal Tax Schedule是近期最基本的。它分为4类,每类有两个等级。下面是其摘要;美元数为应征税的收入。
种类
税金
单身
前17,850美元按15%,超出部分按28%
户主
前23,900美元按15%,超出部分按28%
已婚,共有
前29,750美元按15%,超出部分按28%
已婚,离异
前14,875美元按15%,超出部分按28%
例如,有20000美元应征税收入的单身雇佣劳动者应缴税金0.15X17850美元+0.28+(20000美元-17850美元)。编写一个程序,让用户指定税金种类和应征税收入,然后计算税金。使用循环以便用户可以多次输入。
解:
代码如下:
#include <stdio.h>
#define LEVEL1 17850.0
#define LEVEL2 23900.0
#define LEVEL3 29750.0
#define LEVEL4 14875.0
#define QUIT 5.0
#define RATE1 0.15
#define RATE2 0.28
float chose(void);
void com(float income);
int main(void)
{
    float level;

    while((level = chose()) != QUIT)
        com(level);
    printf("Good Bye!\n");
    return 0;
}
float chose(void)
{
    float level;
    int choice;
 
    do
    {
        printf("**************************************************************************\n");
        printf("Enter the number chose your status:\n");
        printf("1) single                                                             2) houseman\n");
        printf("3) married,common                                           4) married,divorced\n");
        printf("5) quit\n");
        printf("**************************************************************************\n");
        scanf("%d",&choice);
        while(getchar() != '\n'); //scanf()函数在读取数据时,如果不符合格式则会读取失败,该输入仍然在缓冲区中,如果是循环读取,那么就会造成无限循环。这时就需要清空缓存。
        switch(choice)
        {
            case 1:level = LEVEL1;
                       break;
            case 2:level = LEVEL2;
                       break;
            case 3:level = LEVEL3;
                       break;
            case 4:level = LEVEL4;
                       break;
            case 5:level = QUIT;
                       break;
            default:printf("bad choice,try again\n");
        }
    }while(choice < 1 || choice > 5);
    return level;
}
void com(float level)
{
    float salary,tax;

    printf("Input how many dollers is your salary:");
    scanf("%f",&salary);
    if(salary <= level)
        tax = salary * RATE1;
    else
        tax = level * RATE1 + (salary - level) * RATE2;
    printf("tax is %.2f\n",tax);
}
———————————————分割线—————————————————
第十一题:ABC Mail Order Grocery 朝鲜蓟的售价是1.25美元/磅,甜菜的售价是0.65美元/磅,胡萝卜的售价是0.89美元/磅。在添加运输费用之前,他们为100美元的订单提供5%的打折优惠。对5磅或一下的订单收取3.50美元的运输费和装卸费用;超过5磅而不足20磅的订单收取10.00美元的运输和装卸费用;20磅或以上的运输,在8美元的基础上,每磅加收0.1美元。编写程序,在循环中使用switch语句,以便对输入a的响应是让用户所需的朝鲜蓟磅数,b为甜菜的磅数,c为胡萝卜的磅数,而q允许用户退出订购过程。然后程序计算总费用、折扣和运输费用(如果有运输费的话),以及总磅数。随后程序应该显示所有的购买信息:每磅的费用、订购的磅数、该订单每种蔬菜的费用、订单的总费用、折扣,如果有的话加上运输费用,以及所有费用的总数。
解:因为数据过多而导致程序庞大,其实核心不难,关键点在于处理读取和过滤用户输入。
代码如下:
#include <stdio.h>
#define A 1.25
#define B 0.65
#define C 0.89
#define QUIT 5.0
#define CR_D 100.0 
#define CR_D_RATE 0.05
#define CR_P1 5.0
#define CR_P2 20.0
#define CR_P_D1 3.5
#define CR_P_D2 10.0
#define CR_P_D3 8.0
#define CR_P_D_R 0.1
float chose(void);
int main(void)
{
    float type,pan,pan1,pan2,pan3,pans,sum1,sum2,sum3,sum,pay,discount,transport;
    pan1 = 0.0;
    pan2 = 0.0;
    pan3 = 0.0;
    pans = 0.0;
    sum1 = 0.0;
    sum2 = 0.0;
    sum3 = 0.0;
    discount = 0.0;

    while((type = chose()) != QUIT)
    {
        printf("How many pands do you want:\n");
        if(scanf("%f",&pan))
        {
            while(getchar() != '\n');   //过滤非首个数字和回车的垃圾输入缓存。
            if(type == A)
            {    
                sum1 += type * pan;  
                pan1 += pan;
            }
            else if(type == B)
            {    
                sum2 += type * pan;  
                pan2 += pan;
            }

            else
            {    
                sum3 += type * pan;  
                pan3 += pan;
            }

            pans = pan1 + pan2 +pan3;
        }
    }
    pay = sum = sum1 + sum2 + sum3;
    if(sum >= CR_D)
        discount = sum * CR_D_RATE;
    pay -= discount;
    if(pans > 0.0)
    {
        if(pans <= CR_P1)
            transport = CR_P_D1;
        else if(pans < CR_P2)
            transport = CR_P_D2;
        else
            transport = CR_P_D3 + pans * CR_P_D_R;
        pay += transport;
    }

    if(pan1 > 0.0)
        printf("globe artichoke $%.2f/pound,%.2f pounds is ordered,there $%.2f will be added for it\n",A,pan1,sum1);
    if(pan2 > 0.0)
        printf("beet $%.2f/pound,%.2f pounds is ordered,there $%.2f will be added for it\n",B,pan2,sum2);
    if(pan3 > 0.0)
        printf("carrot $%.2f/pound,%.2f pounds is ordered,there $%.2f will be added for it\n",C,pan3,sum3);
    printf("the summary is $%.2f\n",sum);
    if(discount > 0.0)
        printf("the discount is $%.2f\n",discount);
    printf("%.2f pounds goods you will pay $%.2f for it\n",pans,transport);
    printf("so ,finally,you will pay $%.2f for them.\n",pay);
    printf("Good Bye!\n");
    return 0;
}
float chose(void)
{
    float type;
    char choice;
 
    do
    {
        printf("**************************************************************************\n");
        printf("Enter the letter chose your wants:\n");
        printf("a) globe artichoke $%.2f/pound              b) beet $%.2f/pound\n",A,B);
        printf("c) carrot $%.2f/pound  \n",C);
        printf("q) quit\n");
        printf("**************************************************************************\n");
        choice = getchar();
        while(getchar() != '\n');   //过滤非首个字母和回车的垃圾输入缓存。
        switch(choice)
        {
            case 'a':type = A;
                       break;
            case 'b':type = B;
                       break;
            case 'c':type = C;
                       break;
            case 'q':type = QUIT;
                       break;
            default:printf("bad choice,try again\n");
        }
    }while(choice != 'a' && choice != 'b' && choice != 'c' && choice != 'q');
    return type;
}
———————————————分割线—————————————————
附:用python来重做了第十一题,只简化了10余行代码:
#!/usr/bin/env python
A =1.25
B =0.65
C =0.89
QUIT =5.0
CR_D =100.0
CR_D_RATE =0.05
CR_P1 =5.0
CR_P2 =20.0
CR_P_D1 =3.5
CR_P_D2 =10.0
CR_P_D3 =8.0
CR_P_D_R =0.1
def chose():
    while True:
        print "**************************************************************************"
        print "Enter the letter chose your wants:"
        print "a) globe artichoke $%.2f/pound              b) beet $%.2f/pound" % (A,B)
        print "c) carrot $%.2f/pound" % B
        print "q) quit"
        print "**************************************************************************" 
        choice = raw_input()[0]
        if choice == 'a':
            type = A
            pou = input("How many pands do you want:")
            break
        elif choice == 'b':
            type = B
            pou = input("How many pands do you want:")
            break
        elif choice == 'c':
            type = C
            pou = input("How many pands do you want:")
            break
        elif choice == 'q':
            type = QUIT
            pou = 0
            break
        else:
            print "bad choice,try again"
    return (type,pou)
def com():
    pou1 = 0
    pou2 = 0
    pou3 = 0
    sum1 = 0
    sum2 = 0
    sum3 = 0
    while True:
        type,pou = chose()
        if type == QUIT:
            break
        else:
            if type == A:
                sum1 += type * pou
                pou1 += pou
            elif type == B:
                sum2 += type * pou
                pou2 += pou
            else:
                sum3 += type * pou
                pou3 += pou
    return (pou1,pou2,pou3,sum1,sum2,sum3)
def main():
    pou1,pou2,pou3,sum1,sum2,sum3 = com()
    pous = pou1 + pou2 +pou3
    pay = sum = sum1 + sum2 +sum3
    discount = 0
    if sum >= CR_D:
        discount = sum * CR_D_RATE
        pay -= discount
    if pous > 0:
        if pous <= CR_P1:
            transport = CR_P_D1
        elif pous <= CR_P2:
            transport = CR_P_D2
        else:
            transport = CR_P_D3 + pous * CR_P_D_R
        pay += transport
    if pou1 > 0:
        print "globe artichoke $%.2f/pound,%.2f pounds is ordered,there $%.2f will be added for it" % (A,pou1,sum1)
    if pou2 > 0:
        print "beet $%.2f/pound,%.2f pounds is ordered,there $%.2f will be added for it" % (B,pou2,sum2)
    if pou3 > 0:
        print "carrot $%.2f/pound,%.2f pounds is ordered,there $%.2f will be added for it" % (C,pou3,sum3)
    print "the summary is %.2f" % sum
    if discount > 0:
        print "the discount is $%.2f" % discount
    print "%.2f pounds goods you will pay $%.2f for it" % (pous,transport)
    print "so ,finally,you will pay $%.2f for them." % pay
    print "Good Bye!"
if __name__ == "__main__":
    main()











0 0