第7章知识点

相信这里做笔记也是不错的选择

7.1
知识点总结:
(1)!=的优先级比=号要高,把两个行为合并成一个表达式会比较常见;
(2)字符实际是是作为整数存储的;
(3)专门处理字符的函数:ctype.h
(4)整个if else 语句被视为一条语句,因此不必把嵌套的if else语句用花括号括起来。当然,花括号可以更清楚地表明这种特殊格式的含义,最大支持127层嵌套;
(5)如果没有花括号,else会和最近的if匹配;
(6)C逻辑运算符与或非 && || !;
(7)备选拼写:iso646.h;
(8)条件运算符代码更简洁、紧凑;条件运算符优先于==;表达式
expression1 ? expression2 : expression3
(9)continue breaks可以根据测试结果来忽略一部分循环
(10)+=要学会使用;
(11)跳转至while循环的测试条件,在嵌套循环内,只会影响包含该语句的内层循环;好处是减少主语句中的一级缩进,语句较长或嵌套太多时,紧凑简洁的格式提高了代码的可读性;
(12)break用于退出本层循环,而continue为结束本次循环;break只能跳出一层循环,无法跳出所有有循环,把if的测试条件反过来便可避免使用continue;
(13)continue如果没有简化代码反而让代码更复杂,那就不要使用continue;
(14)if else过多嵌套时,可以使用switch和break;
(15)break用于循环和switch语句中,但continue只能用于循环中;
(16)如果是浮点类型的变量或表达式来选择,就无法使用switch;范围也建议使用if else;
(17)胡乱跳转至程序的不同部分。简而言之,不要这样做!但C程序员可以接受一种 goto的用法—出现问题时从一组嵌套循环中跳出(一条break只能跳出当前循环);

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

7.1

//colddays.c--找出0摄氏度以下的天数占总天数的百分比
#include <stdio.h>
int main(viod)
{
    const int FREEZING = 0;
    float temperature;
    int cold_days = 0;
    int all_days = 0;

    printf("Enter the list of daily low temperatures.\n");
    printf("Use Celsius, and enter q to quit.\n");//celsius:摄氏度
    while (scanf("%f", &temperature) == 1)
    {
        all_days++;
        if (temperature < FREEZING)
            cold_days++;
    }
    if (all_days !=0)
        printf("%d days total:%.lf%% were below freezing.\n",
            all_days, 100.0*(float)cold_days / all_days);
    else
        printf("No data entered!\n");
    
    return 0;
}



7.2

// cypher1.c--      更改输入,空格不变
#include <stdio.h>
#define SPACE ' '
int main(void)
{
    char ch;
    ch = getchar();
    while (ch != '\n')  //换行符也可以看做是符号;
    {
        if (ch == SPACE)
            putchar(ch);
        else
            putchar(ch+1);
        ch = getchar();
    }
    putchar(ch);
    return 0;
}
// cypher2.c ---替换输入的字符,非字母字符保持不变
#include <stdio.h>
#include <ctype.h>
int main(void)
{
    char ch;
    while ((ch = getchar()) != '\n')
    {
        if (isalpha(ch))
            putchar(ch + 1);
        else
            putchar(ch);
    }
    putchar(ch);
    return 0;
}

程序清单7.4

//electric.c  --计算电费
#include <stdio.h>
#define RATE1 0.13230                                        //首次使用360kwh的费率
#define RATE2 0.15040                                        //接着再使用108kwh的费率
#define RATE3 0.30025                                        //接着再使用252kwh的费率
#define RATE4 0.34025                                        //超过720kwh的费率
#define BREAK1 360.0                                         //费率的第1个分界点
#define BREAK2 468.0                                         //费率的第2个分界点
#define BREAK3 720.0                                         //费率的第3个分界点
#define BASE1 (RATE1*BREAK1)                                 //使用360kwh的费率
#define BASE2 (BASE1 + (RATE2 *(BREAK2 - BREAK1)))           //使用468kwh的费用
#define BASE3 (BASE1 + BASE2 + (RATE3 *(BREAK3 - BREAK2)))   //使用720kwh的费用
int main(void)
{
    double kwh;                                              //使用的千瓦时
    double bill;                                             //电费

    printf("Please enter the kwh used.\n");
    scanf("%lf", &kwh);
    if (kwh <= BREAK1)
        bill = RATE1 * kwh;
    else if (kwh <= BREAK2)
        bill = BASE1 + (RATE2 * (kwh - BREAK1));
    else if (kwh <= BREAK3)
        bill = BASE2 + (RATE3 * (kwh - BREAK2));
    else
        bill = BASE3 + (RATE4 * (kwh - BREAK3));
    printf("The charge for %.lf kwh is $%1.2f.\n", kwh, bill);

    return 0 ;
}

7.5

// 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 divisible by %lu and %lu.\n", num, div, num / div);
                else
                    printf("%lu is divisible 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");
    
    return 0;
}

7.6

// chcount.c -- 使用嵌套if语句显示一个数的约数
#include <stdio.h>
#define PERIOD '.'
int main(void)
{
    char ch;
    int charcount = 0;

    while ((ch = getchar()) != PERIOD)
    {
        if (ch != '"' && ch != '\'')
            charcount++;
    }
    printf("There are %d non-quote characters.\n", charcount);

    return 0;
}

I didn’t read the “I’m a Programming Fool” best seller.
7.7

//备选拼写:iso646.h
//C99标准新增了可代替逻辑运算符的拼写
//&&  and
//||  or
//!   not
//优先级:!运算符的优先级比乘法运算符还高,与递增运算符的优先级相同,只比圆括号的优先级低;
//空白字符表达式  c != ' ' && c != '\n\ && c! = '\t'       对应函数 isspace(c)
//编写一个统计单词的程序
//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)                     //while循环的目的,统计字符,统计行,统计单词
    {
        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);

    return 0;
}

条件运算符:?:
7.8

/*paint.c -- 使用条件运算符*/
#include <stdio.h>
#define COVERAGE 350
int main(void)
{
    int sq_feet;
    int cans;

    printf("Enter number of square feet to be painted:\n");
    while (scanf("%d", &sq_feet) == 1)
    {
        cans = sq_feet / COVERAGE;
        cans += ((sq_feet % COVERAGE == 0)) ? 0 : 1;
        printf("You need %d %s of paint.\n", cans, cans == 1 ? "can" : "cans");
        printf("Enter next value (q to quit):\n");
    }
    return 0;
}

7.9

#include <stdio.h>
int main(void)
{
    const float MIN = 0.0f;
    const float MAX = 100.0f;

    float score;
    float total = 0.0f;
    int n = 0;
    float min = MAX;
    float max = MIN;

    printf("Enter the first score(<100.0f && >0.0f) (q to quit): ");
    while (scanf("%f", &score) == 1)
    {
        if (score < MIN || score > MAX)
        {
            printf("%0.1f is an invalid value. Try again: ",score);
            continue;//跳转至while循环的测试条件
        }
        printf("Accepting %0.1f:\n",score);
        min = (score < min) ? score : min;
        max = (score > max) ? score : max;
        total += score;
        n++;
        printf("Enter next score (q to quit): ");
    }
    if (n>0)
    {
        printf("Average of %d scores is %0.1f.\n", n, total / n);
        printf("Low = %0.1f, high = %0.1f\n", min, max);
    }
    else
        printf("No valid scores were entered.\n");

        return 0;
}

7.10

/* break.c -- 使用break退出循环*/
#include <stdio.h>
int main(void)
{
    float length, width;

    printf("Enter the length of the rectangle:\n");
    while (scanf("%f", &length) == 1)
    {
        printf("Length = %0.2f:\n", length);
        printf("Enter its width:\n");
        if (scanf("%f", &width) != 1)
            break;
        printf("Width = %0.2f:\n", width);
        printf("Area = %0.2f:\n", length * width);
        printf("Enter the length of the rectangle:\n");
    }
    printf("Done.\n");

    return 0;
}

7.11

/* animals.c -- 使用switch语句*/
#include <stdio.h>
#include <ctype.h>
int main(void)
{
    char ch;

    printf("Give me a letter of the alphabet, and I will give ");
    printf("an animal name\nbeginning with that letter.\n");
    printf("Please type in a letter; type # to end my act.\n");

    while ((ch = getchar()) != '#')
    {
        if (ch == '\n')                                                 //如果ch是换行符,执行下面的if语句
            continue;                                                   //如果直接输入换行符,直接结束本次循环
        if (islower(ch))                                                //排除大写字母
            switch (ch)
            {
                case 'a':
                    printf("argali, a wild sheep of Asia\n");
                    break;
                case 'b':
                    printf("babirusa, a wild pig of Malay\n");
                    break;
                case 'c':
                    printf("coati, racoonlike mammal\n");
                    break;
                case 'd':
                    printf("desman, aquatic, molelike critter\n");
                    break;
                case 'e':
                    printf("fisher, brownish marten\n");
                case 'f':
                    printf("fisher, brownish marten\n");
                default:
                    printf("I recognize only lowercase letters.\n");
           }
        else
            printf("I recognize only lowercase letters.\n");    
        while (getchar() != '\n')                                       //跳过输入行的其余部分  当获取的字符不是换
            continue;                                                   //行符时,跳出while本次循环,继续跑while循环
        printf("Please type another letter or a #.\n");                 //直到看到换行符时,结束whilie条件为0,结束循环
    }
        printf("Bye!\n");

        return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值