【发布时间】:2021-01-06 22:41:15
【问题描述】:
我正在开发一个只有基本运算符的小计算器。它真的很好用,就像我想要的那样。但是有一个小问题。
我的程序在一个循环中,所以理论上用户可以在每次计算后再次使用它。
但我也希望程序能够区分 float 类型的数字和其他所有元素,因此它只接受浮点数或整数。
问题来了: 如果我输入一个字母字符,问题就会变得混乱并且无法正确循环。 您可以在输入一些随机字母而不是预期的两个数字时自己尝试一下。
#include <stdio.h>
#include <unistd.h>
#include <ctype.h>
int main()
{
float num1, num2, result = 0;
int menu;
while (1) //so that the program basically never stops
{
printf("--- Taschenrechner ---\n\n"
"1. Addition\n"
"2. Subtraktion\n"
"3. Multiplikation\n"
"4. Division\n"
"5. Beenden\n"
"Wählen Sie Ihren gewünschten Operator aus (oder auch nicht): ");
// it is like the calculators menu, distinguishing between
// addition, subtraction, multiplication, division and exit
scanf("%d", &menu);
if (menu >= 5 || menu < 1)
{
printf("\nDas Programm wurde beendet, schade. Bis zum nächsten Mal!"); //if the given integer is 5 or not part of the menu, the program should stop
break;
}
printf("\n\nGeben Sie nun zwei Zahlen ein:\n"); //user should provide two numbers
scanf("%f", &num1);
printf("\n");
scanf("%f", &num2);
if ((isalpha(num1) || isalpha(num2)) == 0) //if the given elements are no numbers at all, in this case part of the alphabet, the program should stop
{
printf("Gut!");
} else
{
printf("Break");
break;
}
switch (menu)
{
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
result = num1 / num2;
break;
default:
printf("\n\nUps, da ist wohl etwas mit den Operatoren schief gelaufen. Versuchen Sie es erneut!"); //here again, if something went wrong within the switch case, program should stop
break;
}
printf("\n\nPerfekt, das hat geklappt!");
sleep(1); //this is just for delaying the result
printf("\n\nIhr Ergebnis wird berechnet\nErgebnis: %.2f\n\n\n", result);
sleep(3);
}
return 0;
}
我真的不知道如何解决这个问题,试了几天。解决方案可能真的很简单,但我就是不明白。 一点帮助会非常好。 :)
而且也不介意程序是德语的。我已经将一些东西解释为 cmets。
【问题讨论】:
-
查看
scanf的返回值。这至少会告诉你输入是否可以被解析。但是如果它失败了,你仍然需要消耗无效的输入。建议修改代码使用fgets读取/消费一行输入,然后sscanf解析输入。 -
将浮点数传递给
isalpha不会验证您的输入。
标签: c loops while-loop calculator