c - 变量未更新,While 循环不起作用
问题描述
我正在研究一个累加器,它要求不同的输入,并根据这些输入更新累加器中的值。然而,当我要求输入十进制、十六进制或八进制时,我的循环似乎没有运行。有人可以看看并提出一些建议来解决它吗?谢谢!另外我想在我的 print_menu() 函数中以某种方式使用 while 循环来检查输入是否有效。有什么建议么?
#include <stdio.h>
#include <string.h>
short get_operand(char mode);
void print_acc(short acc);
char print_menu(void);
int main(void);
int main(){
char mode = 'D';
short acc = 8;
char input[10];
char option;
char valid_input[7] = "OHDCSQ";
while (mode != 'Q'){
print_acc(acc);
print_menu();
scanf("%s", &input);
printf("%s\n", input);
option = (char) toupper(input[0]);
switch(option){
case 'O':
mode = 'O';
printf("mode\n");
printf("Mode is Octal\n");
break;
case 'H':
mode = 'H';
printf("Mode is Hexadecimal\n");
break;
case 'D':
mode = 'D';
printf("Mode is Decimal\n");
break;
case 'C':
acc = 0;
break;
case 'S':
get_operand(mode);
if (mode == 'H'){
scanf("%hx", &acc);
printf("%hx", acc);
print_acc(acc);
}
else if (mode == 'O'){
scanf("%ho", &acc);
printf("%ho", acc);
print_acc(acc);
}
else{
scanf("%hd", &acc);
printf("%hd", acc);
print_acc(acc);
}
case 'Q':
mode = 'Q';
printf("\n");
break;
}
//return acc;
}
}
void print_acc(short acc){
printf("\n");
printf("****************************************\n");
printf("* Accumulator: *\n");
printf("* Hex : %04hx *\n", acc);
printf("* Octal : %08ho *\n", acc);
printf("* Decimal : %06hd *\n", acc);
printf("****************************************\n");
}
char print_menu(void){
printf("\n");
printf("Please Select one of the following options:\n");
printf("O Octal Mode\n");
printf("H Hecadecimal Mode\n");
printf("D Decimal Mode\n");
printf("\n");
printf("C Clear Accumulator\n");
printf("S Set Accumulator\n");
printf("\n");
printf("Q Quit\n");
printf("\n");
printf("Option: ");
}
short get_operand(char mode){
switch(mode){
case 'H':
printf("Enter Hex value:");
break;
case 'O':
printf("Enter Octal value:");
break;
default:
printf("Enter decimal value: ");
break;
}
return mode;
}
解决方案
在'S'
您读入数字的情况下,您忘记break
在案例末尾添加声明。这导致代码陷入Q
导致循环退出的情况。
添加break
并且循环将按预期继续:
case 'S':
...
break;
case 'Q':
...
这也是不正确的:
scanf("%s", &input);
%s
期望 a char *
,但您正在传递数组的地址( achar (*)[10]
是 presice )。直接传入数组,这将衰减为指向第一个元素的指针以产生正确的类型:
scanf("%s", input);
另外,更改print_menu
并get_operand
返回void
,因为您没有使用返回值,并且在前一种情况下没有包含一个。
推荐阅读
- python - 在使用 python 的 request.get() 之后,PDF 文件已损坏
- windows - 如何在没有 PNP 的情况下为 Windows 构建服务控制管理器 (SCM) 管理的驱动程序?
- matlab - 有没有办法在matlab中增加一个非数组整数?
- kotlin - Gradle 的初学者问题
- vba - 可变范围的值
- html - 如何在不使用鼠标或某些组合键的情况下转到 VS 代码中的行尾?
- node.js - 为什么 sequelize 只返回一个结果?
- excel - 用于更新 Powerpoint 演示链接的 Excel 代码。文件以只读方式打开
- java - 如何检查类