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);
    }
相关推荐
bkspiderx3 小时前
RabbitMQ 技术指南(C/C++版)
c语言·c++·rabbitmq
你怎么知道我是队长3 小时前
C语言---命令行参数
c语言·开发语言
leaves falling4 小时前
c语言-动态内存管理
c语言·开发语言
一路往蓝-Anbo5 小时前
第37期:启动流程(二):C Runtime (CRT) 初始化与重定位
c语言·开发语言·网络·stm32·单片机·嵌入式硬件
代码游侠5 小时前
ARM嵌入式开发代码实践——LED灯闪烁(C语言版)
c语言·开发语言·arm开发·笔记·嵌入式硬件·学习
麒qiqi6 小时前
进阶 IMX6ULL 裸机开发:从 C 语言点灯到 BSP 工程化(附 SDK / 链接脚本实战)
c语言·开发语言
程序员zgh6 小时前
C++ 纯虚函数 — 抽象接口
c语言·开发语言·c++·经验分享·笔记·接口隔离原则
云深麋鹿6 小时前
一.算法复杂度
c语言·开发语言·算法
夏乌_Wx7 小时前
练题100天——DAY39:单链表练习题×5
c语言·数据结构·算法·链表