我想在Turbo C中制作一个简单的计算器(我有自己的理由为什么我现在使用Turbo C)
#include <stdio.h>
#define P printf
int loop[] = {1, 1, 1, 1};
int num;
char input[64];
void main()
{
int num1, num2;
char x, y;
while(loop[0] == 1)
{
clrscr();
P("Hello!, This simple calculator will help you compute 2 numbers.");
P("\nPress the corresponding key to choose the operation you will use.");
P("\n\nA - (A)ddition");
P("\nS - (S)ubtraction");
P("\nM - (M)ultiplication");
P("\nD - (D)ivision");
P("\n\nAnswer: ");
while(loop[1] == 1)
{
x = getchar();
if(tolower(x) == 'a')
{
P("\nYou have chosen addition.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%d + %d = %d", num1, num2, num1+num2);
}
else if(tolower(x) == 's')
{
P("\nYou have chosen subtraction.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%d - %d = %d", num1, num2, num1-num2);
}
else if(tolower(x) == 'm')
{
P("\nYou have chosen multiplication.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%d * %d = %d", num1, num2, num1*num2);
}
else if(tolower(x) == 'd')
{
P("\nYou have chosen division.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%g* %g = %.2f", (float)num1, (float)num2, (float)(num1/num2));
}
else
{
P("\nYou have entered an invalid character!");
P("\n\nAnswer: ");
continue;
}
while(loop[2] == 1)
{
P("\n\nDo you want to do another calculation? Y/N: ");
y = getchar();
if(tolower(y) == 'y' || tolower(y) == 'n')
{
loop[2] = 0;
}
else
{
P("\nYou have entered an invalid character.");
continue;
}
}
loop[1] = 0;
}
if(tolower(y) == 'y')
{
continue;
}
if(tolower(y) == 'n')
{
loop[0] = 0;
}
}
}
int askForNumber(const char *string)
{
P("%s", string);
while(loop[3] == 1)
{
fgets(input, (sizeof(input)/sizeof(input[0]))-1, stdin);
if(sscanf(input, "%d", &num) != 1)
{
num = 0;
P("Invalid number!");
continue;
}
return num;
}
}
我有这些错误:
完成计算后,按“&#39; Y&#39;”,它会不停地清除屏幕。
&#34;输入第一个号码:&#34;,&#34;无效号码&#34;即使我还没有键入任何内容(但我仍然可以输入一个数字,它将被保存到&#39; num1&#39;,&#34;无效的数字只会让我感到困扰&#34;。
在我要输入的顶部&#39; a&#39;或者&#39; s&#39;或者&#39; m&#39;或者&#39; d&#39;选择一项操作,如果我除了上面的内容之外放了一些字母,我就得到这个
输出:
Answer: o
You have entered an invalid character!
Answer:
You have entered an invalid character!
Answer:
错误显示两次,但我只键入一次。
答案 0 :(得分:0)
当输入缓冲区中没有字符时,getchar
功能将被阻塞,直到按下return
键。所有键(包括return
)都存储在输入缓冲区中,然后getchar
返回缓冲区中的第一个字符。下一次调用getchar
将立即返回缓冲区中的下一个字符。
所以,如果你按下&#39; y&#39;然后return
,第一次拨打getchar
即可返回&#39; y&#39;字符,下一个返回换行符,即return
键。
每次使用getchar
跳过换行符时,都需要刷新输入缓冲区:
do {
c = getchar();
} while (c == '\n');
答案 1 :(得分:-1)
你需要#include ctype.h to lower是该库的一部分tolower使用这个库并且它在你的代码中没有任何地方