第七章 C控制语句:分支和跳转-C primer plus

来源:互联网 发布:mac os x 10.5正式版 编辑:程序博客网 时间:2024/06/06 12:45

2016年8月21日

7.1 if 语句判断一个数是不是素数./* divisors.c -- 使用嵌套if显示一个数的约数*/#include<stdio.h>#include<stdbool.h>int main(void) {    unsigned long num;    // 要检查的数    unsigned long div; // 可能的约数    bool isPrime;    // 素数的标志    printf("Please enter an integer for analysis: ");    printf("Enter q to quit/\n");    while (scanf("%lu",&num)==1)    {        for (div = 2, isPrime = true; (div*div) <= num; div++) {            if (num%div == 0) {                if ((div*div) != num)                    printf("%lu is divisble by %lu and %lu.\n",                        num, div, num / div);                else                    printf("%lu is divisble by %lu.\n", num, div);                isPrime = false;// 不是一个素数            }        }        if (isPrime)            printf("%lu is prime.\n", num);        printf("Please enter another integer for analysis:");        printf("Enter q to quit.\n");    }    printf("Bye.\n");    getchar();    getchar();    return(0);}Please enter an integer for analysis: Enter q to quit/1254112541 is prime.Please enter another integer for analysis:Enter q to quit.1281112811 is divisble by 23 and 557.

/* chcount.c -- 使用逻辑运算符*/#include<stdio.h>#define PERIOD '.'int main(void) {    int ch;    int charcount = 0;    while ((ch=getchar())!=PERIOD)    {        if (ch != '"' && '\'')            charcount++;    }    printf("There are %d non-quote character.\n", charcount);    getchar();    getchar();    return(0);}使用if做排除、剔除alsl''''sd''adsd.There are 16 non-quote character./* wordcnt.c -- 统计字符、单词和行*/#include<stdio.h>#include<ctype.h>    // 为isspace()提供函数原型#include<stdbool.h> // 为bool\true和false提供定义#define STOP '|'int main(void) {    char c; // 读入字符    char prev;    // 前一个读入字符    long n_chars = 0L; // 字符数    int n_lines = 0; // 行数    int n_words = 0;  // 单词数    int p_lines = 0; // 不完整的行数    bool inword = false; // 如果C在一个单词中,则inword 等于true    printf("Enter text to be analyzed(| to terminate):\n");    prev = '\n'; // 用于识别完整的行    // while ((c = getchar()!= STOP))  // 不正确,只读到一个word,并且编译没有错误.    while ((c = getchar())!= STOP)      {        n_chars++; // 统计字符        if (c == '\n')            n_lines++; //统计行数        if (!isspace(c) && !inword)        {            inword = true; // 开始一个新单词            n_words++; // 统计单词        }        if (isspace(c) && inword)            inword = false; // 到达单词尾部        prev = c; // 保存字符值    }    if (prev != '\n')        p_lines = 1;    printf("characters = %ld, words = %d, lines = %d, ",        n_chars, n_words, n_lines);    printf("partial lines = %d\n", p_lines);        getchar();    getchar();    return(0);}Enter text to be analyzed(| to terminate):Reason is apowerful servant butan inadequate master.|characters = 55, words = 9, lines = 3partial lines = 02016822日无论是拼命克服困意熬夜苦读,还是顶着寒风早起上学,这些肉体上的努力是不够的。你必须时刻思考自己有哪些不足,去弥补自己的不足,去向他人请教,去翘掉你已经掌握的课来总结错题,抛弃做过几十遍的题目并把时间拿来做更难的题……这些更需要努力,需要你努力维持头脑的高速运转,努力面对两小时做一张卷却拿到不及格的痛苦,努力放下面子去向同学请教很“弱智”的问题,努力去质疑老师布置任务的合理性……总之,你要战胜自己的懒惰、虚荣、矫情,用一切办法,拼命地弥补自己的弱点,而不是抱着练习册狂刷来营造一种“我已经很努力”的错觉。我觉得爱情不是时刻在一起,而是哪怕在一方需要离开的时候,充分支持她,尽己所能帮助她到达目的地,然后对接下来的重逢满怀信心,双方一起变得更好。爱不是死死抓住,爱是轻松托住。/* paint.c -- 使用条件运算符*/#include<stdio.h>#define COVERANGE 200int main(void) {    int sq_feet=0;    int cans = 0;    printf("Enter number of square feet to be painted: \n");    while (scanf("%d",&sq_feet) == 1)    {        cans = sq_feet / COVERANGE;        cans += ((sq_feet%COVERANGE == 0)) ? 0 : 1;        printf("You need %d %s of the paint.\n", cans,            cans == 1 ? "can" : "cans");        printf("Enter next value(q to quit): \n");    }    return 0;        getchar();    getchar();    return(0);}编程练习:1./*7.12.c -- 字符数 */#include<stdio.h>#include<ctype.h>int main(void) {    int cnt_spc = 0,cnt_n = 0,cnt_other = 0;    char ch;    printf("Please input a string end by#:");    while ((ch=getchar())!='#')    {        if(ch==' ')        cnt_spc ++;        else if (ch == '\n')            cnt_n++;        else            cnt_other++;    }        printf("space count is %d, n is %d, other character is %d", cnt_spc, cnt_n, cnt_other);    printf("\n");        getchar();    getchar();    return(0);}2./*7.12.c --  */#include<stdio.h>int main(void) {    int i = 0;  // 字符数    char ch;    printf("Please input a string end by#:");    for (i=1;ch=getchar()!='#';i++)    {                printf("%c-- %d\t",ch,ch);            if (i%8 == 0)                printf("\n");    }    printf("\n");    getchar();    getchar();    return(0);}Please input a string end by#:a-- 1   -- 1   b sd s s#-- 1   -- 1   -- 1   -- 1   -- 1   -- 1-- 1   -- 13./*7.12.c -- 计算偶数和奇数 */#include<stdio.h>int main(void) {    int i_odd = 0, i_even = 0, sum_odd = 0, sum_even = 0;    int num = 0;    printf("Please input numbers end by(0 to quit):");    while (1)    {        scanf("%d", &num);        if (num == 0) break;        if (num % 2 == 0) {            i_even++;            sum_even += num;        }        else {            i_odd++;            sum_odd += num;        }    }    printf("even number's count:%d and average is %d\n", i_even, sum_even / i_even);    printf("odd number's count:%d and average is %d", i_odd, sum_odd / i_odd);    printf("\n");    getchar();    getchar();    return(0);}Please input numbers end by(0 to quit):2 5 8 6 4 3 0even number's count:4 and average is 5odd number's count:2 and average is 4/*7.12.c -- putchar() 计数的使用 */#include<stdio.h>int main(void) {    int i=0, a = 0, b = 0;    char ch;    printf("Please input string end by(# to quit):");    while ((ch=getchar())!='#')    {        if (ch == '.') {            putchar('!');            a++;        }        else if (ch == '!') {            putchar('!');            putchar('!');            b++;        }        else            putchar(ch);    }        printf("\n the times of '.' replaced by '!':%d\n",a);        printf("\n the times of '!' replaced by '!!':%d\n",b);    getchar();    getchar();    return(0);}Please input string end by(# to quit):sdl.s sdl!sld.!sdl!s sdl!!sld!!!# the times of '.' replaced by '!':2 the times of '!' replaced by '!!':25./*7.12.c -- 计算偶数和奇数 */#include<stdio.h>int main(void) {    int odd_num = 0, even_num = 0, sum_even = 0, sum_odd = 0;    int num = 0;    printf("Please input some integer number.\n");    while (1)    {        scanf("%d", &num);        if (num == 0) break;        switch (num % 2)        {        case 0:            even_num++;            sum_even += num;            break;        case 1:            odd_num++;            sum_odd += num;            break;        }    }    printf("even number's count:%d and average is %d\n", even_num, sum_even / even_num);    printf("odd number's count:%d and average is %d", odd_num, sum_odd / odd_num);    getchar();    getchar();    return(0);}Please input some integer number.12 45 32 15 160even number's count:3 and average is 20odd number's count:2 and average is 306./*7.12.c -- 计算字符串中ei出现的次数 */#include<stdio.h>int main(void){    char former=0,present=0;    int count = 0;    printf("Please enter string within ei,eg. reeive end by #\n");    // while ((present = getchar() != '#'))  // 无法得出count值    while ((present = getchar()) != '#')    {        if ((former == 'e')&&(present == 'i'))            count++;        former = present;            }    printf("ei has apperared %d times\n", count);    getchar();    getchar();    return(0);}Please enter string within ei,eg. reeive end by #ei ie ei lsei#ei has apperared 3 times20168237./*7.12.c -- 计算工资税金 */#include<stdio.h>#define RATE_1 0.15#define RATE_2 0.2#define RATE_3 0.25#define PER_HOUR 10.00#define ADD_HOUR 15.00#define LIMIT 300#define MIDDLE 450int main(void) {    double all_money = 0, hours = 0, left_money = 0, rate_money = 0;    printf("Please input your work hours:");    while (scanf("%lf", &hours)==1)    {        if (hours <= 40) {            all_money = PER_HOUR*hours;            if (PER_HOUR*hours <= LIMIT)                rate_money = all_money*RATE_1;            else                rate_money = (all_money - LIMIT)*RATE_2 + LIMIT*RATE_1;        }        else         {            all_money = PER_HOUR*hours + PER_HOUR*(1.5-1)*(hours - 40);            if (all_money <= MIDDLE)            rate_money = (all_money - LIMIT)*RATE_2 + LIMIT * RATE_1;            else                rate_money = (MIDDLE - LIMIT)*RATE_2 + LIMIT * RATE_1+(all_money-MIDDLE)*RATE_3;        }        left_money = all_money - rate_money;        printf("all money:\t\t%lf\nrate money:\t\t%lf\nleft money:\t\t%lf\n",all_money,rate_money,left_money);    }    getchar();    getchar();    return(0);}Please input your work hours:50all money is 550.000000 rate money is 100.000000 left money is 450.00000040all money is 400.000000 rate money is 65.000000 left money is 335.00000030all money is 300.000000 rate money is 45.000000 left money is 255.0000001all money is 10.000000 rate money is 1.500000 left money is 8.5000000all money is 0.000000 rate money is 0.000000 left money is 0.00000050all money is 550.000000 rate money is 100.000000 left money is 450.000000/*7.12.c -- 计算工资税金 */#include<stdio.h>#define RATE_1 0.15#define RATE_2 0.2#define RATE_3 0.25#define ADD_HOUR 15.00#define LIMIT 300#define MIDDLE 450int main(void){    double all_money = 0, hours = 0, left_money = 0, rate_money = 0, per_hour = 0;    int num = 0;    printf("*********************************************************************\n");    printf("Enter the number corresponding to the desired pay rate or action:\n");    printf("1) $8.75/hr\t\t\t2) $9.33/hr\n");    printf("3) $10.00/hr\t\t\t4) $11.20/hr\n");    printf("5) quit\n");    printf("*********************************************************************\n");    while (scanf("%d", &num) == 1) {        switch (num)        {        case 1:            per_hour = 8.75;            break;        case 2:            per_hour = 9.33;            break;        case 3:            per_hour = 10.00;            break;        case 4:            per_hour = 11.20;            break;        default: printf("quit \n");            return 0;        }        printf("You have selceted $%.2lf\n", per_hour);        printf("input the work hours of a week:");        scanf("%lf", &hours);        if (hours <= 40) {            all_money = per_hour*hours;            if (per_hour*hours <= LIMIT)                rate_money = all_money*RATE_1;            else                rate_money = (all_money - LIMIT)*RATE_2 + LIMIT*RATE_1;        }        else        {            all_money = per_hour*hours + per_hour*(1.5 - 1)*(hours - 40);            if (all_money <= MIDDLE)                rate_money = (all_money - LIMIT)*RATE_2 + LIMIT * RATE_1;            else                rate_money = (MIDDLE - LIMIT)*RATE_2 + LIMIT * RATE_1 + (all_money - MIDDLE)*RATE_3;        }        left_money = all_money - rate_money;        printf("all money:\t\t%lf\nrate money:\t\t%lf\nleft money:\t\t%lf\n", all_money, rate_money, left_money);    }        getchar();        getchar();        return(0);}/*int get_int(void) { // 得到一个合适的数,过滤其他字符。    int num;    char str[40];    while (scanf("%d",&num)!=1)    {        gets(str);        printf("error! %s is not a number. input again.\n", str);    }    while (getchar() != '\n')        return num;}*/*********************************************************************Enter the number corresponding to the desired pay rate or action:1) $8.75/hr                     2) $9.33/hr3) $10.00/hr                    4) $11.20/hr5) quit*********************************************************************1You have selceted $8.75input the work hours of a week:10all money:              87.500000rate money:             13.125000left money:             74.3750002You have selceted $9.33input the work hours of a week:50all money:              513.150000rate money:             90.787500left money:             422.362500/* 9. 显示小于等于该数的素数*/#include<stdio.h>int isprime(int);int main(void) {    int num = 0,i=0;    printf("Please input a positive number:");    while (scanf("%d", &num) == 1) {        printf("all the primes <= %d\n", num);        for(i=2;i<=num;i++)        // if(isprime(i));  // bug        if(isprime(i))                printf("%d\t",i);        printf("\n");    }    getchar();    getchar();    return 0;}int isprime(int n) { // 是素数返回1,不是素数返回0    int div = 0;    for (div = 2; div*div <= n; div++)        if (n % 2 == 0)            return 0;            return 1;} Please input a positive number:11all the primes <= 112       3       5       7       9       115all the primes <= 52       3       5
0 0