如何在不使用任何变量的前提下重写该C语言选择处理代码?
重写后的无变量版代码(processChoice内无变量)
#include <stdio.h> #include <conio.h> // 辅助函数:读取整数并打印,返回读取的值 static int readAndPrintInt() { int input; scanf("%d", &input); printf("%d", input); return input; } int processChoice() { printf("\nMake a Choice (1, 2, 3 or 0): "); switch(readAndPrintInt()) { case 0: printf("\nExiting...\n"); return 0; case 1: printf("\nDrawing rectangle...\n"); return 1; case 2: printf("\nDrawing Right triangle...\n"); return 2; case 3: printf("\nDrawing isosceles triangle...\n"); return 3; default: printf("\n** Invalid Choice! **\n"); return -1; } } void showMenu() { printf("\nMenu:"); printf("\n1. Draw Rectangle"); printf("\n2. Draw Right triangle"); printf("\n3. Draw isosceles triangle"); printf("\n0. Exit program\n"); } int main() { do { showMenu(); } while(processChoice() != 0); return 0; }
关键修改说明
- 移除processChoice内的变量:将原代码中
choice变量的功能拆分到辅助函数readAndPrintInt中,processChoice函数内不再声明任何变量,仅通过调用辅助函数获取输入值并完成打印。 - 清理main函数冗余变量:原main函数中的
x变量未被实际使用,直接删除,简化循环逻辑。 - 完全复现原执行效果:
- 保留了原有的菜单提示、输入值打印、功能分支提示、错误处理逻辑
- 退出条件和返回值与原代码完全一致,程序行为无变化
如果要求全程零变量(包括辅助函数内的变量),可以用递归结合字符读取实现,但可读性较差且依赖严格的输入格式:
#include <stdio.h> #include <conio.h> // 递归读取整数并打印,返回读取的数值 static int readAndPrintInt() { int c = getchar(); if (c == ' ' || c == '\n') { return readAndPrintInt(); } else if (c >= '0' && c <= '9') { int num = readAndPrintInt(); putchar(c); return num * 10 + (c - '0'); } else { ungetc(c, stdin); return 0; } } int processChoice() { printf("\nMake a Choice (1, 2, 3 or 0): "); switch(readAndPrintInt()) { case 0: printf("\nExiting...\n"); return 0; case 1: printf("\nDrawing rectangle...\n"); return 1; case 2: printf("\nDrawing Right triangle...\n"); return 2; case 3: printf("\nDrawing isosceles triangle...\n"); return 3; default: printf("\n** Invalid Choice! **\n"); return -1; } } void showMenu() { printf("\nMenu:"); printf("\n1. Draw Rectangle"); printf("\n2. Draw Right triangle"); printf("\n3. Draw isosceles triangle"); printf("\n0. Exit program\n"); } int main() { do { showMenu(); } while(processChoice() != 0); return 0; }
注意:这个递归版本仍用到了局部变量c和num,如果严格要求完全无变量,只能通过嵌入汇编实现,但这不符合标准C规范,也失去了代码可移植性。
综上,第一个版本是最符合要求且保持可读性的方案,既满足processChoice内无变量的要求,又完全复现原代码的执行效果。
内容的提问来源于stack exchange,提问作者Harshdeep Singh
相关产品推荐
相关产品推荐

