题目:
-
不使⽤全局变量,重写程序清单12.4。
-
程序清单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); }
思路:
-
用自动变量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; } -
还是用自动变量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); }