初学者提问:超初级习题求解
刚刚学C,采用书籍是 Ivor Horton 的《C语言入门经典》第四版。问题来自书中第三章篇尾的习题4.原题:
习题3.4 修改本章最后的计算器例子,让用户选择输入y或Y,以执行另一个计算,输入n或N就结束程序。(注意:这需要实用goto语句,下一章将介绍一个更好的方法。)
我的代码是:
#include <stdio.h>
int main(void)
{
//declare variables
double operand_1 = 0.0;
double operand_2 = 0.0;
char operator = 0;
char restart = 0;
//input algorithm
again: printf("Please enter your algorithm: ");
scanf("%lf %c %lf",&operand_1,&operator,&operand_2);
//calculations
switch (operator) {
case '+':
printf("= %.2lf\n\n",operand_1 + operand_2);
goto yn;
break;
case '-':
printf("= %.2lf\n\n",operand_1 - operand_2);
goto yn;
break;
case '*':
printf("= %.2lf\n\n",operand_1 * operand_2);
goto yn;
break;
case '/':
if (operand_2 == 0) {
printf("Can't divide by 0, please try again.\n\n");
goto again;
} else {
printf("= %.2lf\n\n",operand_1 / operand_2);
goto yn;
}
break;
default:
printf("Incorrect operator, please try again.\n\n");
goto again;
break;
}
//continue or not
yn:
printf("Would you like to continue? (Y/N)\n\n");
scanf("%c",&restart);
if (restart == 'y' || restart == 'Y'){
goto again;
}else if (restart == 'n' || restart == 'N'){
return 0;
}else{
printf("invalid charactor, please enter \"Y\" or \"N\".\n\n");
goto yn;
}
return 0;
}
Run的结果是这样:
Please enter your calculation: 1+1
= 2.00
Would you like to continue? (Y/N)
invalid charactor, please enter "Y" or "N".
Would you like to continue? (Y/N)
进行一次计算后,显示“Would you like to continue? (Y/N)”,然后没有输入"Y" 或 "N"的机会,直接就执行后边的if-else,得到结果“invalid charactor, please enter "Y" or "N".”,再次 goto yn,才停下来让人输入Y/N。
我觉得问题可能出在:从switch方法中的语句 goto yn 之后,printf();后边的scanf();没有执行。可是。。。这是为啥啊。。。难道还有其它问题?我检查了几遍代码,以现有知识没有发现什么明显错误(小弟还没学到循环呢。。。)。
求前辈们帮忙指点。