C primer plus (第六版)第十二章 编程练习第1题

题目:

  1. 不使⽤全局变量,重写程序清单12.4。

  2. 程序清单12.4:

    cpp 复制代码
    #include <stdio.h>
    int units = 0;         /* 外部变量  */
    void critic(void);
    int main(void)
    {
         extern int units;  /* 可选的重复声明 */
         printf("How many pounds to a firkin of butter?\n");
         scanf("%d", &units);
         while (units != 56)
              critic();
         printf("You must have looked it up!\n");
         return 0;
    }
    void critic(void)
    {
         /* 删除了可选的重复声明 */
         printf("No luck, my friend. Try again.\n");
         scanf("%d", &units);
    }

思路:

  1. 用自动变量units代替全局变量units,此时需要critic()函数带返回值并将返回值赋值给unit用来和56进行比较;

    cpp 复制代码
    #include <stdio.h>
    int critic(void);
    int main()
    {
        int units;
        
        printf("How many pounds to a firkin of butter?\n");
        scanf("%d",&units);
        while (units != 56)
            units = critic();
        printf("You must have looked it up!\n");
        return 0;
    }
    
    int critic(void)
    {
        int temp;
        printf("No luck, my friend. Try again.\n");
        scanf("%d", &temp);
        return temp;
    }
  2. 还是用自动变量units代替全局变量units,不同的是critic()函数只传入units的指针地址,输入的数据是通过直接修改相同指针下的数据实现的。

    cpp 复制代码
    #include <stdio.h>
    void critic(int * pt);
    int main()
    {
        int units;
            
        printf("How many pounds to a firkin of butter?\n");
        scanf("%d", &units);
        while (units != 56)
        {
            critic(&units);
        }
        printf("You must have looked it up!\n");
        return 0;
    }
    void critic(int * pt )
    {
        printf("No luck, my friend. Try again.\n");
        scanf("%d", pt);
    }
相关推荐
祈安_1 天前
C语言内存函数
c语言·后端
norlan_jame3 天前
C-PHY与D-PHY差异
c语言·开发语言
czy87874753 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237173 天前
C语言-数组练习进阶
c语言·开发语言·算法
Z9fish3 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法
代码无bug抓狂人3 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
CodeJourney_J3 天前
从“Hello World“ 开始 C++
c语言·c++·学习
枫叶丹43 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
with-the-flow3 天前
从数学底层的底层原理来讲 random 的函数是怎么实现的
c语言·python·算法
Sunsets_Red3 天前
P8277 [USACO22OPEN] Up Down Subsequence P 题解
c语言·c++·算法·c#·学习方法·洛谷·信息学竞赛