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);
    }
相关推荐
晓13131 天前
第二章 【C语言篇:入门】 C 语言基础入门
c语言·算法
jiang_changsheng1 天前
环境管理工具全景图与深度对比
java·c语言·开发语言·c++·python·r语言
前端玖耀里1 天前
Linux C/C++ 中系统调用与库函数调用的区别
linux·c语言·c++
进击的小头1 天前
设计模式与C语言高级特性的结合
c语言·设计模式
代码无bug抓狂人1 天前
C语言之可分解的正整数(蓝桥杯省B)
c语言·开发语言·算法
历程里程碑1 天前
21:重谈重定义理解一切皆“文件“及缓存区
linux·c语言·开发语言·数据结构·c++·算法·缓存
恶魔泡泡糖1 天前
51单片机I2C-EEPROM
c语言·单片机·嵌入式硬件·51单片机
jiang_changsheng1 天前
MCP协议的核心架构基础
c语言·开发语言·c++·python·comfyui
1+α1 天前
工业通讯中的“顶梁柱”——RS485科普
c语言·stm32·嵌入式硬件·网络协议
晓13131 天前
第三章 【C语言篇:结构化编程】 分支循环数组函数
c语言