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);
    }
相关推荐
为何创造硅基生物5 小时前
C语言 结构体内存对齐规则(通俗易懂版)
c语言·开发语言
仰泳之鹅5 小时前
【C语言】自定义数据类型2——联合体与枚举
c语言·开发语言·算法
jolimark6 小时前
C语言自学攻略:小白入门三步走
c语言·编程入门·学习路线·实践项目·自学攻略
cen__y7 小时前
Linux12(Git01)
linux·运维·服务器·c语言·开发语言·git
社交怪人7 小时前
【算平均分】信息学奥赛一本通C语言解法(题号2071)
c语言·开发语言
卢锡荣8 小时前
单芯通吃,盲插标杆 —— 乐得瑞 LDR6020,Type‑C 全场景互联 “智慧芯”
c语言·开发语言·计算机外设
AI科技星8 小时前
《数学公理体系·第三部·数术几何》(2026 年版)
c语言·开发语言·线性代数·算法·矩阵·量子计算·agi
kkeeper~9 小时前
0基础C语言积跬步之字符函数与字符串函数(上)
c语言·开发语言
東隅已逝,桑榆非晚10 小时前
字符函数和字符串函数
c语言·笔记
AI科技星13 小时前
第二章 平行素数对网格:矩形→等腰梯形拓扑变换(完整公理终稿)
c语言·开发语言·线性代数·算法·量子计算·agi