使用一个非常简单的计算器程序,提示用户执行一项操作,然后提示输入两个整数以执行该操作。程序应该在这些操作之后循环,除非用户输入字符'q',此时程序应该退出。
#include <stdio.h>
int main (void)
{
char c;
int number[2], num1, num2, result;
double num1d, num2d, resultd;
int done=1;
while(done)
{
printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n");
c = getchar();
printf("\tplease enter a number \n");
scanf("%d",&number[0]);
printf("\tplease enter another number \n");
scanf("%d",&number[1]);
num1 = number[0];
num2 = number[1];
switch(c)
{
case('-'):
result = num1-num2;
printf("\nThe first number you entered subtracted by the second number is %d.\n", result);
break;
case('+'):
result = num1+num2;
printf("The first number you entered added to the second number is %d.\n", result);
break;
case('*'):
result = num1*num2;
printf("The first number you entered multiplied with the second number is %d.\n", result);
break;
case('/'):
num1d = (double) num1;
num2d = (double) num2;
resultd = num1d/num2d;
printf("The first number you entered divided by the second number is %g.\n", resultd);;
break;
case('q'):
printf(" Now Exiting...\n");
done=0;
break;
default:
puts("Invalid key pressed. Press q to exit");
break;
}
}
return 0;
}
对单个计算正常工作,但随后执行异常;特别是它打印
printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n");
printf("\tplease enter a number \n");
共。
清除输入缓冲区的标准方法while (getchar() != '\n');
不能解决这个问题。此文本显示不正确的两倍,用户仍然可以使用程序,就好像指令显示正常一样(因此用户可以键入操作,例如 +,回车,然后是一些整数和回车,并且程序将从那时起正确执行)每隔一次程序将“按下无效键。按 q 退出”,无论输入如何。