zoukankan      html  css  js  c++  java
  • C Primer Plu学习笔记【5-6章节】

    第五章 运算符、表达式和语句

    5.1 循环介绍

    示例代码

    #include <stdio.h>
    #define  ADJUST 7.31
    
    int main(void)
    {
        
        const double SCALE = 0.333;
        double shoe, foot;
        
        shoe = 9.0;
        foot = SCALE * shoe + ADJUST;
        printf("Shoe size (men's)    foot length
    ");
        printf("%10.1f %15.2f inches
    ", shoe, foot);
        
        return 0;
    }

    输出

    Shoe size (men's)    fott length

           9.0           10.31 inches

    Program ended with exit code: 0

    示例代码,增加while循环

    #include <stdio.h>
    #define  ADJUST 7.31
    
    int main(void)
    {
        
        const double SCALE = 0.333;
        double shoe, foot;
        
        
        printf("Shoe size (men's)    foot length
    ");
        shoe = 3.0;
        while (shoe < 18.5) {    /* 块开始 */
            foot = SCALE * shoe + ADJUST;
            printf("%10.1f %15.2f inches
    ", shoe, foot);
            shoe = shoe + 1.0;
        }               /* 块结束*/
        
        printf("If the shoe fits,wear it.
    ");
        
        return 0;
    }
    

      输出

    Shoe size (men's)    foot length

           3.0            8.31 inches

           4.0            8.64 inches

           5.0            8.97 inches

           6.0            9.31 inches

           7.0            9.64 inches

           8.0            9.97 inches

           9.0           10.31 inches

          10.0           10.64 inches

          11.0           10.97 inches

          12.0           11.31 inches

          13.0           11.64 inches

          14.0           11.97 inches

          15.0           12.30 inches

          16.0           12.64 inches

          17.0           12.97 inches

          18.0           13.30 inches

    If the shoe fits,wear it.

    Program ended with exit code: 0

    while后面花括号以及花括号括起来的部分被称为块(block)

    几个术语

    数据对象是用于储存值的数据存储区域统称为数据对象。

    左值为可修改左值或者对象定位符

    右值可以是常量、变量或其他可求职的表达式。

    示例代码=号的连续赋值

    示例代码:

    #include <stdio.h>
    
    int main(void)
    {
        int jane, tarzan, cheeta;
        
        cheeta = tarzan = jane = 68;
        printf("                cheeta    tarzan    jane
    ");
        printf("First round score %4d %8d %8d
    ", cheeta, tarzan, jane);
        
        return 0;
    }

    输出

                    cheeta    tarzan    jane

    First round score   68       68       68

    Program ended with exit code: 0

    5.2.5 指数增长

    示例代码

    int main(void)
    {
        const double CROP = 2E16; // 世界小麦年产颗粒数
        double current, total;
        int count = 1;
        
        printf("square    grains       total        ");
        printf("fraction of 
    ");
        printf("          added        grains       ");
        printf("world total
    ");
        total = current = 1;    // 初始化第一颗
        printf("%4d %13.2e %12.2e %12.2e
    ", count, current,
               total, total / CROP);
        while (count < SQUARES) {
            count = count + 1;
            current = current * 2.0;
            total = total + current;
            printf("%4d %13.2e %12.2e %12.2e
    ", count, current,
                   total, total / CROP);
        }
        printf("That's all.
    ");
        
        return 0;
    }
    

      部分输出

     52      2.25e+15     4.50e+15     2.25e-01

      53      4.50e+15     9.01e+15     4.50e-01

      54      9.01e+15     1.80e+16     9.01e-01

      55      1.80e+16     3.60e+16     1.80e+00

      56      3.60e+16     7.21e+16     3.60e+00

      57      7.21e+16     1.44e+17     7.21e+00

    55时候的,总数就大于全球小麦年产量了。

    5.2.6除法运算符:/

    示例代码

    #include <stdio.h>
    
    int main(void)
    {
        printf("integer divsion: 5/4  is %d
    ", 5/4);
        printf("integer divsion: -5/4  is %d
    ", -5/4);
        printf("integer divsion: 6/3  is %d
    ", 6/3);
        printf("integer divsion: 7/4  is %d
    ", 7/4);
        printf("integer divsion: -7/4  is %d
    ", -7/4);
        printf("floating divsion: 7./4. is %1.2f
    ", 7./4.);
        printf("maixed divsion: 7./4  is %1.2f
    ", 7./4);   // 尽量避免混合数字类型操作。
        
        return 0;
    }
    

      输出

    integer divsion: 5/4  is 1

    integer divsion: -5/4  is -1

    integer divsion: 6/3  is 2

    integer divsion: 7/4  is 1

    integer divsion: -7/4  is -1

    floating divsion: 7./4. is 1.75

    maixed divsion: 7./4  is 1.75

    Program ended with exit code: 0

    5.2.8优先级和求值顺序

    小括号优先,后面是一元操作符优先,后面乘除加减

    示例代码

    #include <stdio.h>
    
    int main(void)
    {
        int top, score;
        
        top = score = -(2+5) * 6 + (4 + 3 *(2+3));
        printf("top = %d, score = %d
    ", top, score);
        
        return 0;
    }
    

      输出

    top = -23, score = -23

    Program ended with exit code: 0

    5.3 其他远算符

    5.3.1 sizeof运算符和size_t类型

    示例代码

    #include <stdio.h>
    
    int main(void)
    {
        int n = 0;
        size_t intsize;
        
        intsize = sizeof(int);
        printf("n = %d, n has %zd bytes; all ints have %zd bytes.
    ",
               n, sizeof n, intsize);
        return 0;
    }
    

      输出

    n = 0, n has 4 bytes; all ints have 4 bytes.

    Program ended with exit code: 0

    5.3.2求模运算符 %

    Python中叫取余运算符, 求模运算符只能用于整数,不能用于浮点数。

    示例代码

    #include <stdio.h>
    #define SEC_PER_MIN 60
    int main(void)
    {
        int sec, min, left;
        
        printf("Convert seconds to minutes and seconds!
    ");
        printf("Enter the number of seconds (<0 to quit):
    ");
        scanf("%d", &sec);
        while (sec > 0) {
            min = sec / SEC_PER_MIN;  // 分钟
            left = sec % SEC_PER_MIN; // 剩下的秒速
            printf("%d seconds is %d minutes, %d seconds.
    ", sec,
                   min, left);
            printf("Enter the number of seconds (<0 to quit):
    ");
            scanf("%d", &sec);
        }
        printf("Done!
    ");
        
        return 0;
    }
    

      输出

    Convert seconds to minutes and seconds!

    Enter the number of seconds (<0 to quit):

    156

    156 seconds is 2 minutes, 36 seconds.

    Enter the number of seconds (<0 to quit):

    120

    120 seconds is 2 minutes, 0 seconds.

    Enter the number of seconds (<0 to quit):

    0

    Done!

    5.3.3 递增运算符:++

     示例代码,前缀模式,后缀模式

    #include <stdio.h>
    
    int main(void)
    {
        int ultra = 0, super = 0;
        
        while (super < 5) {
            super++;
            ++ultra;
            printf("super = %d,ultra = %d 
    ", super, ultra);
        }
        
        return 0;
    }

    输出

    super = 1,ultra = 1
    super = 2,ultra = 2
    super = 3,ultra = 3
    super = 4,ultra = 4
    super = 5,ultra = 5
    Program ended with exit code: 0

    我们可以再前面的代码中带条件携程这样

    shoe = 2.0;

    while (++shoe < 18.5)

    {

        foot = ...

    }

    当进行赋值的时候,前缀模式与后缀模式不一样。

    示例代码

    #include <stdio.h>
    
    int main(void)
    {
        int a = 1, b = 1;
        int a_post, pre_b;
        
        a_post = a++;
        pre_b = ++b;
        printf("a  a_post   b   pre_b 
    ");
        printf("%1d %5d %5d %5d
    ", a, a_post, b, pre_b);
        
        return 0;
    }

    输出

    a  a_post   b   pre_b
    2     1     2     2
    Program ended with exit code: 0

    从输出可以看到,a与b都发生了变化,但赋值的时候,只要++b的复制表达式,得到了b+1的值

    书中有比较仔细的解释。

    递减运算符也一样逻辑。

    5.3.5 优先级

    递增运算符和递减运算符都有很高的结合优先级,只有圆括号的优先级比它们高。

    在一个n++是表达式的一部分,可将其视为"先使用n,再递增";而++n则辩识"先递增n,再使用"。

    5.3.6 不要自作聪明

    ++的使用指南

    如果一个变量出现再一个函数的多个参数中,不要对该变量使用递增或递减运算符

    如果一个变量多次出现在一个表达式中,不要对该变量使用递增或递减表达式。

    5.4 表达式和语句

    5.4.1 表达式

    好抽象的概念:表达式(expression)由运算符和愿算对象组成(运算对象就是运算符操作的对象)。最简单的表达式视一个单独的运算对象,以此为基础可以建立复杂的表达式。

    每个表达式都有一个值

    5.4.2 语句

    语句(statement)是C程序的基本构建块。一条语句相当于一条完整的计算机指令。在C中,大部分语句都以分号结尾。

    语句一般改变值,或者调用函数。

    示例代码

    #include <stdio.h>
    int main(void)      /* 计算前20个整数的和*/
    {
        int count, sum;   /* 申明, 申明不是表达式*/
        
        count = 0;       /* 表达式语句*/
        sum = 0;         /* 表达式语句*/
        while (count++ < 20)       /* 迭代语句*/
            sum = sum + count;
        printf("sum = %d
    ", sum);    /* 表达式语句*/
        
        return 0;      /* 跳转语句*/
        
    }

    副作用和序列点

    语句的副作用是对数据对象和文件的修改,主要目的是对表达式求值。

    序列点(sequence point)是程序执行的点,在该点上,所有的副作用都在下一步之前发生。在C语言中,语句中的分号标记了一个序列点。

    意思是,在一个语句中,赋值运算符、递增运算符和递减运算符对运算对象左的改变必须在程序执行下一条语句之前完成。

    完整表达式(full expression)就视指这个表达式不是另一个更大的表达式的子表达式。

    表达式语句中的表达式和while循环中的作为测试条件的表达式,都是完整表达式。

    5.4.3复合语句(块)

    复合语句(compound statement)是用话括号括起来的一条或多条语句,复合语句也称为块(block);

    总结:

    表达式由运算符和运算对象组成,最简单的就是一个运算对象。

    语句:

    简单语句以分号结尾

    复合语句(块)由花括号括起来的一条或多条语句组成。

    5.5类型转换

    示例代码

    #include <stdio.h>
    int main(void)
    {
        char ch;
        int i;
        float fl;       // 以定义的类型优先,转换成定义的类型
        
        fl = i = ch = 'C';                  // C为67
        printf("ch = %c, i = %d, fl = %2.2f
    ", ch, i, fl);  /* 整形可以直接赋值给浮点型数字*/
        ch ++;                              // ch + 1
        i = fl + 2*ch;                  // 67 + 2 * 68 = 203
        fl = 2.0*ch +i;                 //68 *2 + 203 = 339
        printf("ch = %c, i = %d, fl = %2.2f
    ", ch, i, fl);
        ch = 1107;                  // 1107 % 256 = 1107- 1024= 83
        printf("Now ch = %c = %d
    ", ch, ch);
        ch = 80.89;                 // 浮点给整形赋值,直接切除小数点部分
        printf("Now ch = %c = %d
    ", ch, ch);
        return 0;
    }

    输出

    ch = C, i = 67, fl = 67.00

    ch = D, i = 203, fl = 339.00

    Now ch = S = 83

    Now ch = P = 80

    Program ended with exit code: 0

    5.5.1  强制类型转换运算符

    使用(type)

    总结前面学过的运算符

    赋值运算符:

    =  将其右侧的值赋给左侧的变量

    算术运算符:

    +  将其左侧的值与右侧的值相加

    -  将其左侧的值减去右侧的值

    -  作为一元运算符,改变其右侧值的符号

    *  将其左侧的值乘以右侧的值

    /  将其左侧的值除以右侧的值,如果两数都是整数,计算机构将被截断。

    %  当其左侧的值除以右侧的值时,取其余数(只能应用与整数)

    ++  当其右侧的值加1(前缀模式),或对其左侧的值加1(后缀模式)

    --  当其右侧的值减1(前缀模式),或对其左侧的值减1(后缀模式)

    其他运算符:

    sizeof    获得其右侧运算对象的大小(以字节为单位),运算对象可以是一个被圆括号括起来的类型说明符,如sizeof(float),或者是一个具体的变量名、数组名等,如sizeof foo

    (类型名)  强制类型转换运算符将其右侧的值转换成圆括号中指定的类型,如(float)9把整数9转换成浮点数9.0

    5.6 带参数的函数

     示例代码

    #include <stdio.h>
    
    void pound(int n);          /*  ANSI函数原型申明*/
    int main(void)
    {
        int times = 5;
        char ch = '!';
        float f = 6.0f;
        
        pound(times);           /*  调用函数  */
        pound(ch);
        pound(f);
        
        return 0;
    }
    
    void pound(int n)
    {
        while (n-- > 0) {
            printf("#");
        }
        printf("
    ");
    }

    输出

    #####

    #################################

    ######

    Program ended with exit code: 0

    书中介绍了老式的ANSI之前的函数

    void pound();

    书中253也由详细的说明,为什么这个不行。

    5.7示例程序

    #include <stdio.h>
    
    const int S_PER_M = 60;             // 1分钟的秒数
    const int S_PER_H = 3600;           // 1小时的秒速
    const double M_PER_K = 0.62137;      // 1公里的英里数   这个定义在主函数的外面,成为全局变量
    
    int main(void)
    {
        double distk, distm;    // 跑过的距离(分别以公里和英里为单位)
        double rate;            // 平均速度(以英里/小时为单位)
        int min, sec;           // 跑步用时(以分钟和秒为单位)
        int time;               // 跑步用时(以秒为单位)
        double mtine;           // 跑一英里需要的时间,以秒为单位
        int mmin, msec;         // 跑一英里需要的时间,以分钟和秒为单位
        
        printf("This program converts your time for a metic race
    ");
        printf("to a time for running a mile and to your average
    ");
        printf("seppd in miles per hour.
    ");
        printf("Please enter, in kilometers, the distance run.
    ");
        scanf("%lf", &distk);        // %lf表示读取一个double类型的值
        printf("Next enter the time in minutes and seconds.
    ");
        printf("Begin by entering the minutes.
    ");
        scanf("%d", &min);
        printf("Now enter rhe seconds.
    ");
        scanf("%d", &sec);
        
        time = S_PER_M * min + sec;      // 把时间转换成秒
        distm = M_PER_K * distk;            /* 把公里转换成英里 */
        rate = distm / time * S_PER_H;      // 多少英里每小时的速度
        mtine = (double)time / distm;       // 跑一英里需要的秒时间  这里用到了显式强制类型转换
        mmin = (int)mtine / S_PER_M;     // 求出分钟数
        msec = (int)mtine % S_PER_M;     // 求出剩余的秒速
        
        printf("You ran %1.2f km (%1.2f mils) in %d min, %d sec.
    ",
               distk, distm, min, sec);
        printf("That pace corresponds to running a mile in %d min, ",
               mmin);
        printf("%d sec.
    Your average speed was %1.2f mph.
    ", msec, rate);
        
        
        return 0;
    }

    输出

    This program converts your time for a metic race

    to a time for running a mile and to your average

    seppd in miles per hour.

    Please enter, in kilometers, the distance run.

    10

    Next enter the time in minutes and seconds.

    Begin by entering the minutes.

    36

    Now enter rhe seconds.

    23

    You ran 10.00 km (6.21 mils) in 36 min, 23 sec.

    That pace corresponds to running a mile in 5 min, 51 sec.

    Your average speed was 10.25 mph.

    Program ended with exit code: 0

    5.10复习题

    a 30

    b 27

    c y 1 x 1

    d y 9 x 3

    2

    6

    52

    0

    13

    第三题

    37.5

    1.5

    35

    37

    37.5

    35.0

    第四题

    #include <stdio.h>
    
    int main()
    {
        int i = 1;
        float n;
        printf("Watch out ! Here come a bunch of fractions!
    ");
        while (++i < 30) {
            n = 1.0 / i;
            printf(" %f", n);
        }
        printf("That's all, folks!
    ");
        return 0;
    }

    第五题

    代码有逻辑问题,在while条件使用参数的时候,尽然还没有通过canf传入参数。

    第六题

    %s! C is cool!

     C is cool!     ->! C is cool!

    11

    11

    12

    11

    第7题

    SOS:4 4.00 

    第8题

    1到10,前面空4个,右对齐。

    第九题

    #include <stdio.h>
    #define TEN 10
    
    int main(void)
    {
        int n = 0;
        while (n++ < TEN) {
            printf("%5c
    ", n+96);    \ A从ASCI65开始,a从97开始
        }
        printf("
    ");
        return 0;
    }

    第十题

    a                        -->   1   2

        1

        2

    b

     101

     102

     103

    c

    sw            ->stuvw

    第十一题

    死循环输出

    COMPUTER BYTES DOG

     

    第十二题

    a

    x = x+10

    b

    x++

    c

    c = (a+b)*2

    d

    c = a + b * 2

    第十三题

    a

    x--

    b

    m = n % k

    c

    p = q / b -a

    d

    x = (a + b) / (c * d)

    5.11编程练习

    第一题

    #include <stdio.h>
    
    int main(void)
    {
        const int min_ch_hou = 60;
        int min;
        printf("请输入分钟时间:");
        scanf("%d", &min);
        while (min > 0) {
            printf("你输入的%d分钟就是%d小时%d分钟.
    ",min, min/min_ch_hou,min%min_ch_hou);
            printf("请输入分钟时间:");
            scanf("%d", &min);
        }
        printf("退出");
        return 0;
    }

    输出

    请输入分钟时间:90

    你输入的90分钟就是1小时30分钟

    请输入分钟时间:30

    你输入的30分钟就是0小时30分钟

    请输入分钟时间:0

    退出Program ended with exit code: 0

    第二题

    #include <stdio.h>
    
    int main(void)
    {
        int number;
        printf("请输入一个数字:
    ");
        scanf("%d", &number);
        while (number <= 15) {
            printf("%d	", number);
            number++;
        }
        printf("
    ");
        
        return 0;
    }

    输出

    请输入一个数字:

    5

    5 6 7 8 9 10 11 12 13 14 15

    第三题

    #include <stdio.h>
    
    int main(void)
    {
        const int days_ch_week = 7;
        int days_num, remain_days, week_num;
        
        printf("Please input the number of days:
    ");
        scanf("%d", &days_num);
        while (days_num > 0) {
            week_num = days_num / days_ch_week;
            remain_days = days_num % days_ch_week;
            printf("%d days are %d weeks, %d day.
    ", days_num, week_num, remain_days);
            printf("Please input the number of days:
    ");
            scanf("%d", &days_num);
        }
        printf("done.
    ");
        
        return 0;
    }

    输出

    Please input the number of days:

    19

    19 days are 2 weeks, 5 day.

    Please input the number of days:

    -1

    done.

    第四题

    #include <stdio.h>
    #define FEET_CM 30.48
    #define INCHES_CM 2.54
    
    int main(void)
    {
        float in_message, inches_num;
        int feet_num;
        
        printf("Enter a height in centimeters:");
        scanf("%f", &in_message);
        while (in_message > 0) {
            feet_num = (int)in_message/FEET_CM;
            inches_num = (in_message - feet_num * FEET_CM)/INCHES_CM;
            printf("%.1f cm = %d feet, %.1f inches
    ", in_message, feet_num, inches_num);
            printf("Enter a height in centimeters:");
            scanf("%f", &in_message);
            
        }
        printf("done.
    ");
        
        return 0;
    }

    输出

    Enter a height in centimeters:182

    182.0 cm = 5 feet, 11.7 inches

    Enter a height in centimeters:168.7

    168.7 cm = 5 feet, 6.4 inches

    Enter a height in centimeters:0

    done.

    Program ended with exit code: 0

    第五题

    #include <stdio.h>
    
    int main(void)
    {
        int count, sum = 0, index = 0;
        
        printf("Please input the days:");
        scanf("%d", &count);
        while (index++ < count) {
            sum = sum + index;
        }
        printf("sum = %d
    ", sum);
        
        return 0;
    }

    输出

    Please input the days:100

    sum = 5050

    Program ended with exit code: 0

    第六题

    #include <stdio.h>
    
    int main(void)
    {
        int count, sum = 0, index = 0;
        
        printf("Please input the days:");
        scanf("%d", &count);
        while (index++ < count) {
            sum = sum + index * index;
        }
        printf("sum = %d
    ", sum);
        
        return 0;
    }

    输出

    Please input the days:100

    sum = 338350

    Program ended with exit code: 0

    第七题

    #include <stdio.h>
    
    void calculate(double number);
    
    int main(void)
    {
        double in_num;
        printf("Please input the number:");
        scanf("%lf", &in_num);
        calculate(in_num);
        return 0;
        
    }
    
    void calculate(double number){
        printf("%.3f的立方=%.3f
    ", number,number*number*number);
    }

    输出

    Please input the number:3.1415

    3.142的立方=31.004

    Program ended with exit code: 0

    第八题

    #include <stdio.h>
    
    int main(void)
    {
        int first_num, second_num;
        printf("This program computes moduli.
    ");
        printf("Enter an integer to serve as the second operand: ");
        scanf("%d", &second_num);
        printf("Now enter the first operand: ");
        scanf("%d", &first_num);
        while (first_num > 0) {
            printf("%d %% %d is %d
    ", first_num, second_num, first_num % second_num);
            printf("Enter next number for first operand (<=0 to qunit): ");
            scanf("%d", &first_num);
        }
        printf("Done
    ");
        
        return 0;
    }

    输出

    This program computes moduli.

    Enter an integer to serve as the second operand: 256

    Now enter the first operand: 438

    438 % 256 is 182

    Enter next number for first operand (<=0 to qunit): 1234567

    1234567 % 256 is 135

    Enter next number for first operand (<=0 to qunit): 0

    Done

    Program ended with exit code: 0

    第九题

    #include <stdio.h>
    
    void Temperatures(double fahrenheit);
    
    int main(void)
    {
        double fahrenheit;
        int out;
        printf("Please input fahrenheit (q is out):");
        out = scanf("%lf", &fahrenheit);
        while (out) {
            Temperatures(fahrenheit);
            printf("Please input fahrenheit:(q is out)");
            out = scanf("%lf", &fahrenheit);
        }
        printf("Done
    ");
        
        return 0;
    }
    
    void Temperatures(double fahrenheit)
    {
        const double cen_kel = 273.16;
        double degree_centigrade, degree_kelvin;
        degree_centigrade = 5.0/9.0*(fahrenheit - 32.0);
        degree_kelvin = degree_centigrade + cen_kel;
        printf("fahrenheit is %.2f = degree centigrade %.2f = degree kelvin %.2f.
    ",
               fahrenheit, degree_centigrade ,degree_kelvin);
    }

    输出

    Please input fahrenheit (q is out):100

    fahrenheit is 100.00 = degree centigrade 37.78 = degree kelvin 310.94.

    Please input fahrenheit:(q is out)q

    Done

    Program ended with exit code: 0

    第6章  C控制语句: 循环

    6.1 再探while循环

    示例代码

    #include <stdio.h>
    int main(void)
    {
        long num;
        long sum = 0L;      /*  把sum初始化为0   */
        int status;
        
        printf("Please enter an integr to be summed ");
        printf("(q to quit): ");
        status = scanf("%ld", &num);
        while (status == 1) {
            sum = sum + num;
            printf("Please enter next integer (q to quit): ");
            status = scanf("%ld", &num);
        }
        printf("Those integers sum to %ld.
    ", sum);
        
        return 0;
    }

    输出

    Please enter an integr to be summed (q to quit): 44

    Please enter next integer (q to quit): 33

    Please enter next integer (q to quit): 88

    Please enter next integer (q to quit): 121

    Please enter next integer (q to quit): q

    Those integers sum to 286.

    Program ended with exit code: 0

    6.1.2 C风格读取循环

    ...

    6.2.2合适终止循环

    示例代码

    #include <stdio.h>
    int main(void)
    {
        int n = 5;
        
        while (n < 7) {
            printf("n = %d
    ",n);
            n++;     // 自增加1
            printf("Now n = %d
    ", n);
        }
        printf("The loop has finished.
    ");
        
        return 0;
    }

    输出

    n = 5

    Now n = 6

    n = 6

    Now n = 7

    The loop has finished.

    Program ended with exit code: 0

    6.2.4语法要点

    使用while时,要牢记一点:只有在测试条件后面单独与拒(简单语句或复合语句)才是循环部分。

    如果在测试条件后面直接上单独的分号是空语句(null statement)。在C语言钟,单独的分号表示空语句。

    6.3用关系运算符和表达式比较大小

    关系远算符大于或者小于跟Python完全一样。

    关系运算符可用来比较浮点数,但是要注意,在比较浮点数时,尽量只使用<和>。因为浮点数的舍入误差会导致在逻辑上应该相等的两个数不相等。

    示例代码

    #include <math.h>
    #include <stdio.h>
    int main(void)
    {
        const double ANSWER = 3.14159;
        double response;
        
        printf("What is the value of pi?
    ");
        scanf("%lf", &response);    // double用lf接收
        while (fabs(response - ANSWER) > 0.0001) {    //fabs 来至math.h的头文件
            printf("Try again!
    ");
            scanf("%lf", &response);
        }
        printf("Close enough!
    ");
        
        return 0;
    }

    输出

    What is the value of pi?
    3.14
    Try again!
    3.1416
    Close enough!
    Program ended with exit code: 0

    6.3.1 什么是真

    对C而言,表达式为真的值是1,表达式为假的值是0;

    示例代码

    #include <stdio.h>
    int main(void)
    {
        int true_val, false_val;
        
        true_val = (10 > 2);
        false_val = (10 == 2);
        printf("true = %d; false = %d
    ", true_val, false_val);
        
        return 0;
    }

    输出

    true = 1; false = 0

    Program ended with exit code: 0

    6.3.2 其他真值

    只要测试条件的值非零,就会执行while循环

    示例代码

    #include <stdio.h>
    
    int main(void)
    {
        int n = 3;
        while (n) {
            printf("%2d is true
    ", n--);
        }
        printf("%2d is false
    ", n);
        
        n = -3;
        while (n) {
            printf("%2d is true
    ", n++);
        }
        printf("%2d is false
    ", n);
        
        return 0;
    }

    输出

     3 is true

     2 is true

     1 is true

     0 is false

    -3 is true

    -2 is true

    -1 is true

     0 is false

    Program ended with exit code: 0

    6.3.3 真值的问题

    许多经验丰富的程序员在构建比较是否相等的表达式时,都习惯把常量放在左侧。

    6.4.1 新的_Bool类型

    C99专门针对这种类型新增了_Bool类型。该类型是以英国数学家George Boole的名字命名的。

    示例代码

    #include <stdio.h>
    int main(void)
    {
        long num;
        long sum = 0L;      /*  把sum初始化为0   */
        _Bool status;
        
        printf("Please enter an integr to be summed ");
        printf("(q to quit): ");
        status = scanf("%ld", &num);
        while (status) {
            sum = sum + num;
            printf("Please enter next integer (q to quit): ");
            status = scanf("%ld", &num);
        }
        printf("Those integers sum to %ld.
    ", sum);
        
        return 0;
    }

    _Bool 形式的使用,C99提供了stdbool.h的头文件,该头文件让bool称为_Bool的别名。

    6.5 for 循环

    示例代码

    #include <stdio.h>
    int main(void)
    {
        const int NUMVER = 3;
        int count;
        for (count = 1; count <= NUMVER; count++)
            printf("Be my Valentine!
    ");
        
        printf("count = %d
    ", count);
        return 0;
    }

    输出

    Be my Valentine!

    Be my Valentine!

    Be my Valentine!

    count = 4

    Program ended with exit code: 0

    书中的逻辑图很不错。

    示例代码

    #include <stdio.h>
    int main(void)
    {
        
        int num;
        
        printf("    n  n cubed
    ");
        for (num = 1; num <= 6; ++num)
            printf("%5d %6d
    ",num, num * num * num);
        return 0;
    }

    输出

        n  n cubed

        1      1

        2      8

        3     27

        4     64

        5    125

        6    216

    Program ended with exit code: 0

    6.5.1 利用for循环

    for循环的其他用法

    可以使用递减运算符来递减计数器

    #include <stdio.h>
    int main(void)
    {
        int secs;
        
        for (secs = 5; secs > 0; secs--)
        printf("%d seconds!
    ", secs);
        printf("We have ignition!
    ");
        
        return 0;
    }

    输出

    5 seconds!

    4 seconds!

    3 seconds!

    2 seconds!

    1 seconds!

    We have ignition!

    Program ended with exit code: 0

    自定义初始值,与递增值

    #include <stdio.h>
    int main(void)
    {
        int n;
        for (n = 2; n < 60; n = n+13) {
            printf("%d 
    ", n);
        }
        return 0;
    }

    输出

    2 

    15 

    28 

    41 

    54 

    Program ended with exit code: 0

    可以用字符代替数字计算

    #include <stdio.h>
    int main(void)
    {
        char ch;
        
        for (ch = 'a'; ch <= 'z'; ch++) {
            printf("The ASCII value for %c is %d.
    ", ch, ch);
        }
        
        return 0;
    }

    第三个表达式可以使用任意合法表达式

    #include <stdio.h>
    int main(void)
    {
        int x;    // 不给初始值,也是从0开始
        int y = 52;
        
        for (x = 1; y <= 75; y = (++x * 5) + 50) {
            printf("%10d %10d
    ", x, y);
        }
        
        return 0;
    }

    输出

             1         52

             2         60

             3         65

             4         70

             5         75

    Program ended with exit code: 0

    可以省略一个或多个表达式(但是不能省略分号)

    #include <stdio.h>
    int main(void)
    {
        int ans, n;
        ans = 2;
        for (n = 3; ans <= 25;) {
            ans = ans * n;
        }
        printf("n = %d; ans = %d.
    ", n, ans);
        
        return 0;
    }

    输出

    n = 3; ans = 54.

    Program ended with exit code: 0

    for (;;)

      printf("I want some action. ");

    上面的会一直循环执行。

    第一个表达式不一定是给变量赋初值,也可以使用printf()。记住,在执行循环的其他部分之前,只对第一个表达式求值一次或执行一次。

    #include <stdio.h>
    int main(void)
    {
        int num = 0;    // 用于比较的时候,第一次要赋值,++的时候可以不赋值
        
        for (printf("Keep entering numbers!
    "); num !=6; ) {
            scanf("%d", &num);
        }
        printf("That's the one I want!
    ");
        
        return 0;
        
    }

    输出

    Keep entering numbers!

    1

    2

    3

    6

    That's the one I want!

    Program ended with exit code: 0

    循环体钟的行为可以改变循环头重的表达式。

    其他赋值运算符:+=,-=,*=,/=,%=

    6.7 逗号运算符

    示例代码

    #include <stdio.h>
    int main(void)
    {
        const int FIRST_OZ = 46;
        const int NEXT_OZ = 20;
        int ounces, cost;
        
        printf(" ounces  cost
    ");
        for (ounces = 1, cost = FIRST_OZ; ounces <=16; ounces++, cost += NEXT_OZ) {
            printf("%5d  %4.2f
    ", ounces, cost / 100.);
        }
        return 0;
    }

    输出

     ounces  cost

        1  0.46

        2  0.66

        3  0.86

        4  1.06

        5  1.26

        6  1.46

        7  1.66

        8  1.86

        9  2.06

       10  2.26

       11  2.46

       12  2.66

       13  2.86

       14  3.06

       15  3.26

       16  3.46

    Program ended with exit code: 0

    逗号运算符并不局限在for循环钟使用,但这是它最常用的地方。逗号运算符由两个其他性质,首相,它保证了被它分割的表达式从左向右求值(换言之,逗号是一个序列点,所以逗号左侧项的所有副作用都在程序执行逗号右侧项之前发生)。其次,整个逗号表达式的值是右侧项的值。

    逗号也可用作分隔符,比如

    char ch, date;

    printf("%d %d ", chumps, chimps)

    6.7.1 当Zeno遇到for循环

    示例代码

    #include <stdio.h>
    
    int main(void)
    {
        int t_ct;       // 项计算
        double time, power_of_2;
        int limit;
        
        printf("Enter the number of terms you want: ");
        scanf("%d", &limit);
        for (time = 0, power_of_2 = 1, t_ct = 1; t_ct <= limit; t_ct++, power_of_2 *=2.0) {
            time += 1.0 /power_of_2;
            printf("time = %f when terms = %d.
    ", time, t_ct);
        }
        
        return 0;
    }

    输出

    Enter the number of terms you want: 6

    time = 1.000000 when terms = 1.

    time = 1.500000 when terms = 2.

    time = 1.750000 when terms = 3.

    time = 1.875000 when terms = 4.

    time = 1.937500 when terms = 5.

    time = 1.968750 when terms = 6.

    Program ended with exit code: 0

    6.8 出口条件循环: do while

    执行执行一次

    示例代码

    #include <stdio.h>
    int main(void)
    {
        const int secret_code = 13;
        int code_entered;
        
        do {
            printf("To enter the triskaidekaphobia therapy club,
    ");
            printf("please enter the secret code number: ");
            scanf("%d", &code_entered);
        } while (code_entered != secret_code);
        printf("COngratulations! You are cured!
    ");
        
        return 0;
    }

    输出

    To enter the triskaidekaphobia therapy club,

    please enter the secret code number: 8

    To enter the triskaidekaphobia therapy club,

    please enter the secret code number: 13

    COngratulations! You are cured!

    do后面的执行域,一定会执行一次。

    使用while循环与能写,稍微多一点代码

    #include <stdio.h>
    int main(void)
    {
        const int secret_code = 13;
        int code_entered;
        
        
        printf("To enter the triskaidekaphobia therapy club,
    ");
        printf("please enter the secret code number: ");
        scanf("%d", &code_entered);
        while (code_entered != secret_code){
            printf("To enter the triskaidekaphobia therapy club,
    ");
            printf("please enter the secret code number: ");
            scanf("%d", &code_entered);
        }
        printf("COngratulations! You are cured!
    ");
        return 0;
    }

    6.9 如何选择循环

    首先要确定需要入口条件循环还是出口条件循环。通常,入口条件循环用的比较多,由几个原因。其一,一般原则在执行循环之前测试条件比较好。其二,测试放在循环的开始,程序的可读性更高。另外,在许多应用钟,要求在一开始不满足测试条件时就直接跳过整个循环。

    for与while的选择

    for (;test;) 与while(test)效果相同.

    一般而言,当循环涉及初始化和更新变量时候,用for循环比较合适,而在其他情况下,用while循环更好。

    6.10 嵌套循环

    示例代码

    #include <stdio.h>
    #define ROWS 6
    #define CHARS 10
    int main(void)
    {
        int row;
        char ch;
        
        for (row = 0; row < ROWS; row++) {
            for (ch = 'A'; ch < ('A' + CHARS); ch++) {
                printf("%c", ch);
            }
            printf("
    ");
        }
        return 0;
    }

    输出

    ABCDEFGHIJ

    ABCDEFGHIJ

    ABCDEFGHIJ

    ABCDEFGHIJ

    ABCDEFGHIJ

    ABCDEFGHIJ

    Program ended with exit code: 0

    6.10.2

    嵌套变式

    #include <stdio.h>
    int main(void)
    {
        const int ROWS = 6;
        const int CHARS = 6;
        int row;
        char ch;
        
        for (row = 0; row < ROWS; row++) {
                for (ch = ('A' + row); ch < ('A' + CHARS); ch++) {   // 初始值ch,每次大循环改变,发生变换
                    printf("%c", ch);
                }
                printf("
    ");
            }
            return 0;
    }

    输出

    ABCDEF

    BCDEF

    CDEF

    DEF

    EF

    F

    Program ended with exit code: 0

    6.11 数组介绍

    数组(array)是按顺序存储的一系列类型相同的值。C编译器不会价差数组的下标是否正确。字符数组不是字符串,字符串是字符数组,字符串最后由了一个的空字符。

    6.11.1 在for循环钟使用数组

    示例代码

    #include <stdio.h>
    #define SIZE 10
    #define PAR 72
    int main(void)
    {
        int index, score[SIZE];     // 定一个score的数组
        int sum = 0;
        float average;
        
        printf("Enter %d golf scores:
    ",SIZE);
        for (index = 0; index < SIZE; index++) {
            scanf("%d", &score[index]);      // 写入10个数据
        }
        for (index = 0; index < SIZE; index++) {
            printf("%5d", score[index]);        // 验证输入
        }
        printf("
    ");
        for (index = 0; index < SIZE; index++) {
            sum += score[index];
        }
        average = (float)sum / SIZE;             // 强制准换成浮点型,求平均
        printf("Sum of cores  = %d, average = %.2f
    ", sum, average);
        printf("That's a handicap of %.0f.
    ", average - PAR);
        
        printf("average[10]  = %d
    ", score[10]);   // 输入的时候,多放入一个试试
        return 0;
        
    }

    输出

    Enter 10 golf scores:

    99

    95

    109 105 100

    96 98 93 99 97 98

       99   95  109  105  100   96   98   93   99   97

    Sum of cores  = 991, average = 99.10

    That's a handicap of 27.

    average[10]  = -764739454

    Program ended with exit code: 0

    从运行可以看出,数组超出变量取值,赋值都是可以的,但都是无效的。

    6.12 使用函数返回值的循环示例

    编写一个有返回值的函数,要完成以下内容

    1.定义函数时,确定函数的返回类型

    2.使用关键字return表明待返回的值。

    示例代码

    #include <stdio.h>
    double power(double n ,int p);     // ANSI函数原型声明
    int main(void)
    {
        double x, xpow;
        int exp;
        
        printf("Enter a number and the positive integer power");
        printf(" to which
    the number will be raised. Enter q");
        printf(" to quit.
    ");
        
        while (scanf("%lf%d", &x, &exp) == 2) {      /* 通过返回值的形式来设定条件 ,两个复合要求scanf会返回2 */
            xpow = power(x, exp);       // 调用函数
            printf("%.3g to the power %d is %.5g
    ", x, exp, xpow);
            printf("Enter next pair of numbers or q to quit.
    ");
        }
        printf("Hopre you enjoyed this power trip --bye!
    ");
        
        return 0;
    }
    
    double power(double n, int p){     // 定义函数
        double pow = 1;
        int i;
        
        for (i = 1; i <= p; i++) {
            pow *= n;
        }
        return pow;
    }

    输出

    Enter a number and the positive integer power to which

    the number will be raised. Enter q to quit.

    1.2 12

    1.2 to the power 12 is 8.9161

    Enter next pair of numbers or q to quit.

    2

    16

    2 to the power 16 is 65536

    Enter next pair of numbers or q to quit.

    q

    Hopre you enjoyed this power trip --bye!

    Program ended with exit code: 0

    6.12.2 使用带返回值的函数

    声明函数、调用函数、定义函数、使用关键字return, 都是定义和使用返回值函数的基本要素。

    6.13 关键概念

    循环时一个强大的编程工具。以下3点要注意

    1.注意循环的测试条件要能使循环结束。

    2.确保循环测试中的值在首次使用之前已初始化

    3.确保循环在每次迭代都更新测试的值。

    使用函数的三个步骤

    通过函数原型申明函数

    在程序中通过函数调用使用函数

    定义函数

    函数原型是为了方便编译器查看程序中使用的函数是否正确,函数定义描述了函数如何工作。现代的编程习惯把函数要素分为接口部分和实现部分,列如函数原型和函数定义。接口部分描述了如何使用一个特性,开业就时函数原型所做的。实现部分描述了具体的行为,这正是函数定义所做的。

    6.15复习题

    第一题

    7 ,70,  64, 8, 2

    第二题

    输出 36, 18, 9, 4, 2,  1    [数字三个字符空间宽度]

    如果是double形式,会输出很多,很多

    第三题

    x >5

    scanf("%lf",&x)

    x == 5

    第四题

    scanf("%d", &d)

    x !=5

    x >=20

    第五题

    #include <stdio.h>
    int main(void)
    {
        int i, j, list[10];
        
        for (i = 0; i <10; i++) {
            list[i] = 2*i +3;
            for (j = 0; j < i; j++) {
                printf(" %d", list[j]);
            }
            printf("
    ");
        }
        
        return 0;
        
    }

    输出

     3

     3 5

     3 5 7

     3 5 7 9

     3 5 7 9 11

     3 5 7 9 11 13

     3 5 7 9 11 13 15

     3 5 7 9 11 13 15 17

     3 5 7 9 11 13 15 17 19

    第六题

    #include <stdio.h>
    int main(void)
    {
        int i, j;
        for (i=0; i<4; i++) {
            for (j=0; j<8; j++) {
                printf("$");
            }
            printf("
    ");
        }
        
        return 0;
    }

    第七题

    #include <stdio.h>
    
    int main(void)
    {
        int i = 0;
        
        while (++i < 4) {
            printf("Hi! ");
        }
        do {
            printf("Bye! ");
        }while (i++ < 8);
        
        return 0;
    }

    输出

    Hi! Hi! Hi! Bye! Bye! Bye! Bye! Bye! 

    #include <stdio.h>
    int main(void)
    {
        int i;
        char ch;
        for (i = 0, ch = 'A';i < 4 ; i++, ch += 2 * i) {
            printf("%c", ch);
        }
        return 0;
    }

    输出

    ACGM

    第8题

    Go West, youn

    Hp....

    Go west, young

    $o wast, youn

    第九题

    第十题

    第十一题

    #include <stdio.h>
    #define SIZE 8
    int main(void)
    {
        int by_twos[SIZE];
        int index;
        
        for (index=0; index < SIZE; index++) {
            by_twos[index] = 2 * (index+1);
        }
        for (index=0; index < SIZE; index++) {
            printf("%d ", by_twos[index]);
        }
        printf("
    ");
        
        return 0;
    }

    输出

    2 4 6 8 10 12 14 16 

    第十三题

    把num的类型强制转换成long类型,确保计算使用long类型而不是int类型。在int为16为的系统中,两个int类型值的乘积在返回值钱会被截断为一个int类型的值,这可能会丢失数据

    long square (int num)
    {
         return ((long) num) * num  
    }

    6.16编程练习

    第一题

    #include <stdio.h>
    int main(void)
    {
        char ch = 'a',end_ch;
        char ch_array[26];
        int index;
        for (end_ch = ch + 26; ch <=end_ch; ch++) {
            ch_array[ch - 'a'] = ch;
        }
        for (index=0; index<26; index++) {
            printf("%c", ch_array[index]);
        }
        printf("
    ");
        return 0;
    }

    输出

    abcdefghijklmnopqrstuvwxyz

    第二题

    #include <stdio.h>
    int main(void)
    {
        int i, j;
        for (i=0; i<5; i++) {
            for (j=1; j<=i+1; j++) {
                printf("$");
            }
            printf("
    ");
        }
        return 0;
    }
    

      输出

    $

    $$

    $$$

    $$$$

    $$$$$

    第三题

    #include <stdio.h>
    int main(void)
    {
        char ch = 'F';
        int i, j;
        for (i=1; i<=6; i++) {
            for (j=1; j<=i; j++) {
                printf("%c", ch);
                ch--;
            }
            printf("
    ");
            ch = 'F';
        }
        
        return 0;
    }

    输出

    F

    FE

    FED

    FEDC

    FEDCB

    FEDCBA

    第四题

    #include <stdio.h>
    int main(void)
    {
        char ch = 'A';
        int i,j;
        for (i=1; i<=6; i++) {
            for (j=1; j<=i; j++) {
                printf("%c", ch);
                ch++;
            }
            printf("
    ");
        }
        
        return 0;
    }
    

      输出

    A

    BC

    DEF

    GHIJ

    KLMNO

    PQRSTU

    第五题:想了好久

    #include <stdio.h>
    int main(void)
    {
        
        const char FIRST_CH ='A';
        char first_ch, middle_ch, ch;
        int init, disparity,last,space_disparity;
        printf("Please input a char:");
        scanf("%c",&ch);
        printf("
    ");
        disparity = ch - FIRST_CH;    /* 差距用于处理for循环*/
        for (init = 0; init <= disparity; init++) {
            // 处理空格
            for (space_disparity = 0; space_disparity < disparity-init; space_disparity++) {
                printf(" ");
            }
            // 处理升序的逻辑
            for (first_ch = FIRST_CH; first_ch <= FIRST_CH + init; first_ch++) {
                printf("%c",first_ch);
            }
            // 处理降序的逻辑
            for (middle_ch = FIRST_CH + init - 1; middle_ch >= FIRST_CH; middle_ch--) {
                printf("%c",middle_ch);
            }
            
            printf("
    ");
        }
        
        
        
        return 0;
    }

    输出

    Please input a char:Z

     

                             A

                            ABA

                           ABCBA

                          ABCDCBA

                         ABCDEDCBA

                        ABCDEFEDCBA

                       ABCDEFGFEDCBA

                      ABCDEFGHGFEDCBA

                     ABCDEFGHIHGFEDCBA

                    ABCDEFGHIJIHGFEDCBA

                   ABCDEFGHIJKJIHGFEDCBA

                  ABCDEFGHIJKLKJIHGFEDCBA

                 ABCDEFGHIJKLMLKJIHGFEDCBA

                ABCDEFGHIJKLMNMLKJIHGFEDCBA

               ABCDEFGHIJKLMNONMLKJIHGFEDCBA

              ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA

             ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA

            ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA

           ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA

          ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA

         ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA

        ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA

       ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA

      ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA

     ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA

    ABCDEFGHIJKLMNOPQRSTUVWXYZYXWVUTSRQPONMLKJIHGFEDCBA

    Program ended with exit code: 0

    第六题

    #include <stdio.h>
    
    int main(void)
    {
        int min, max,o_num;
        printf("Please input two number, one is min ,one is max:");
        o_num = scanf("%d%d",&min,&max);
        printf("o_num = %d
    ", o_num);
        for (min; min <= max; min++) {
            printf("The number is %d, square is %d, cube is %d.
    ",
                   min, min * min, min * min * min);
        }
        
        return 0;
    }

    输出

    Please input two number, one is min ,one is max:5 9

    o_num = 2

    The number is 5, square is 25, cube is 125.

    The number is 6, square is 36, cube is 216.

    The number is 7, square is 49, cube is 343.

    The number is 8, square is 64, cube is 512.

    The number is 9, square is 81, cube is 729.

    Program ended with exit code: 0

    第七题

    #include <string.h>
    #include <stdio.h>
    
    int main(void)
    {
        char string[100];
        int index;
        printf("Please input a string:
    ");
        scanf("%s", string);
        for (index = (int)strlen(string) - 1; index>=0; index--) {
            printf("%c", string[index]);
        }
        printf("
    ");
        
        return 0;
        
    }

    输出

    Please input a string:

    love

    evol

    第八题

    #include <stdio.h>
    int main(void)
    {
        double nu_1, nu_2;
        printf("Please input two float number:");
        while (2 == scanf("%lf%lf",&nu_1, &nu_2)) {
            printf("num1 = %f, num2 = %f, result is %.6f
    ",nu_1, nu_2, (nu_1 - nu_2)/(nu_1 * nu_2));
        }
        
        return 0;
    }
    

      输出

    Please input two float number:1 1.2 4 1.5 q

    num1 = 1.000000, num2 = 1.200000, result is -0.166667

    num1 = 4.000000, num2 = 1.500000, result is 0.416667

    Program ended with exit code: 0

    第九题

    #include <stdio.h>
    
    double calculate(double nu_1,double nu_2);
    int main(void)
    {
        double nu_1, nu_2, res;
        printf("Please input two float number:");
        while (2 == scanf("%lf%lf",&nu_1, &nu_2)) {
            res = calculate(nu_1,nu_2);
        }
        printf("num1 = %f, num2 = %f, result is %.6f
    ",nu_1, nu_2, (nu_1 - nu_2)/(nu_1 * nu_2));
        
        return 0;
    }
    
    double calculate(double nu_1, double nu_2){
        double res;
        res = (nu_1 - nu_2)/(nu_1 * nu_2);
        return res;
    }

    输出

    Please input two float number:1 2

    q

    num1 = 1.000000, num2 = 2.000000, result is -0.500000

    Program ended with exit code: 0

     第十题

    #include <stdio.h>
    
    int main(void)
    {
        int min, max, result=0, init;
        printf("Enter lower and upper integer limits:");
        scanf("%d%d", &min, &max);
        while (min < max) {
            for (init=min; init <= max; init++) {
                result += init * init;
            }
            printf("The sums of the squares from %d to %d is %d.
    ",min*min, max*max, result);
            printf("Enter lower and upper integer limits:");
            scanf("%d%d", &min, &max);
            result = 0;
        }
        printf("Done
    ");
        return 0;
    }

    输出

    Enter lower and upper integer limits:5 9

    The sums of the squares from 25 to 81 is 255.

    Enter lower and upper integer limits:3 25

    The sums of the squares from 9 to 625 is 5520.

    Enter lower and upper integer limits:5

    5

    Done

    Program ended with exit code: 0

    第十一题

    #include <stdio.h>
    int main(void)
    {
        int list[8], i;
        printf("Please input eight number:
    ");
        for (i = 0; i < 8; i++) {
            scanf("%d", &list[i]);
        }
        for (i = 7; i >= 0; i--) {
            printf("%d", list[i]);
        }
        printf("
    ");
        
        return 0;
    }

    输出

    Please input eight number:

    1 2 3 4 5 6 7 8

    87654321

    第十二题

    #include <stdio.h>
    
    int main(void)
    {
        double sums, sums2;
        int i, loop_num;
        printf("Please input the loops number:");
        scanf("%d", &loop_num);
        while (loop_num > 0) {
            for (i=1, sums = 0.0; i<=loop_num; i++) {
                sums += 1.0 / i;
            }
            printf("first: %d loop, result = %f
    ",loop_num, sums);
            for (i=1, sums = 0.0; i<=loop_num; i+=2) {
                sums += 1.0 / i;
            }
            for (i=2, sums2 = 0.0; i<=loop_num; i+=2) {
                sums2 += -1.0 / i;
            }
            printf("second: %d loop, result = %f
    ",loop_num, sums + sums2);
            printf("Please input the loops number:");
            scanf("%d", &loop_num);
        }
        printf("Done.
    ");
        
        return 0;
    }
    Please input the loops number:100
    first: 100 loop, result = 5.187378
    second: 100 loop, result = 0.688172
    Please input the loops number:1000
    first: 1000 loop, result = 7.485471
    second: 1000 loop, result = 0.692647
    Please input the loops number:10000
    first: 10000 loop, result = 9.787606
    second: 10000 loop, result = 0.693097
    Please input the loops number:0
    Done.
    

      二式趋于0.7

    第十三题

    #include <stdio.h>
    
    int main(void)
    {
        int list[8], list_cent, i=1;
        for (list_cent=0; list_cent<=7; list_cent++) {
            list[list_cent] = i;
            i *= 2;
        }
        i = 0;
        do
        {
            printf("%d ", list[i]);
            i++;
            
        } while(i <= 7);
        
        printf("
    ");
        return 0;
    }

    输出

    1 2 4 8 16 32 64 128 

    Program ended with exit code: 0

    第十四题

    #include <stdio.h>
    int main(void)
    {
        double f_list1[8], f_list2[8],sums = 0.0;
        int i;
        printf("Please input eight number:
    ");
        for (i = 0; i < 8; i++) {
            scanf("%lf", &f_list1[i]);
            sums += f_list1[i];
            f_list2[i] = sums;
        }
        for (i = 0; i < 8; i++) {
            printf("%6.2f", f_list1[i]);
        }
        printf("
    ");
        for (i = 0; i < 8; i++) {
            printf("%6.2f", f_list2[i]);
        }
        printf("
    ");
        
        return 0;
    }

    输出

    Please input eight number:

    1 2.0 0.3 4 5 1 2 3

      1.00  2.00  0.30  4.00  5.00  1.00  2.00  3.00

      1.00  3.00  3.30  7.30 12.30 13.30 15.30 18.30

    Program ended with exit code: 0

    第十五题

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        char ch[255], one_ch;
        int i = 0;
        printf("input some char:
    ");
        scanf("%c", &one_ch);
        while (one_ch != '
    ') {
            ch[i] = one_ch;
            i++;
            scanf("%c", &one_ch);
        }
        for (i = 0; i < strlen(ch); i++) {
            printf("%c", ch[i]);
        }
        
        printf("
    ");
        
        return 0;
    }

    输出

    input some char:

    1.23.sd ds. w.d sd3.2 d

    1.23.sd ds. w.d sd3.2 d

    第十六题

    #include <stdio.h>
    int main(void)
    {
        double single = 100.0,  compound = 100.0;
        int i = 1;
        
        while (single >= compound) {
            single = 100 * (1+0.1 * i);
            compound *= 1.05;
            i++;
        }
        printf("%d year single money is %f, compound money is %f.
    ", i - 1, single, compound);
        
        return 0;
    }

    输出

    27 year single money is 370.000000, compound money is 373.345632.

    第17题

    #include <stdio.h>
    int main(void)
    {
        double money = 100., i = 0;
        while (money > 0) {
            money *= (1 + 0.08);
            money -= 10;
            i++;
        }
        printf("%.0fyear.
    ", i);
        return 0;
    }

    输出

    21year.

    第21年末尾的时候,取走10万就是负数了。

    第十八题

    #include <stdio.h>
    int main(void)
    {
        int init = 5, i = 1;
        
        while (init <= 150) {
          // 这里放在处理之后,printf,所以会打印超出150范围的情况. init
    = (init - i) * 2; printf("%d week, you firends is %d. ", i, init); i++; } return 0; }

    输出

    1 week, you firends is 8.

    2 week, you firends is 12.

    3 week, you firends is 18.

    4 week, you firends is 28.

    5 week, you firends is 46.

    6 week, you firends is 80.

    7 week, you firends is 146.

    8 week, you firends is 276.

  • 相关阅读:
    父亲节前参考四级考试
    rpm小解
    oracle忘记sys/system/scott用户的密码怎么办
    yum 小解
    linux下设置swap文件
    启动mysql 报错: ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2)
    mysql 常用命令
    wget安装
    删除mysql
    什么是swap分区
  • 原文地址:https://www.cnblogs.com/sidianok/p/14027619.html
Copyright © 2011-2022 走看看