c - C 中的计算器应该只接受浮点数/整数
问题描述
我正在研究一个只有基本运算符的小计算器。它真的很好用,就像我想要的那样。但是有一个小问题。我的程序在一个循环中,所以理论上用户可以在每次计算后再次使用它。但我也希望程序能够区分类型数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;
}
我真的不知道如何解决这个问题,现在尝试了几天。解决方案可能真的很简单,但我就是不明白。一点帮助会非常好。:)
而且也不介意程序是德语的。我已经解释了一些东西作为评论。
解决方案
您应该检查返回的值scanf
。例如:if( scanf("%d", &menu) == 1 ) { ... }
。如果输入流的下一个字符不是有效整数的一部分,则上面scanf
将返回 0。
通常,您应该始终检查 scanf 返回的值。
推荐阅读
- python - 创建包含两个包含列表的 pandas df 列的字典的列
- django - 在 iframe 中购物
- android - 如何在 Compose 中使用密封类正确建模 UI 状态?
- sql - 累积计数返回比预期更多的行
- tensorflow - Jupyter - 笔记本 ModuleNotFoundError:没有名为“object_detection”的模块
- html - 试图将元素的边框设置为白色以隐藏另一个元素的边框
- airflow - Airflow DAG 中的 `schedule_interval=None` 和 `start_date=airflow.utils.dates.days_ago(n)` 的含义?
- python - 逗号分隔的 ids 字符串映射到 python Pandas 中的值
- assembly - 汇编中变量的旧值在哪里?
- laravel - 我如何在 laravel 中建立深层关系?