c - 如何重新初始化变量(CCS 102)(程序 C)
问题描述
在为我们的计算器项目取得进展并重写了大部分代码之后,我遇到了一个问题。
正如标题所示,我需要帮助在循环后或每个循环中重新初始化变量。
问题:
它应该像这样:
如您所见,它仍然计算而不是提示错误,表明输入的 int 存储在我的变量中。我可能错了或其他什么,但如果我不能解决这些问题,我会取得更大的进步。
这是代码:
#include <stdio.h>
#include <stdbool.h>
//bool function
bool isInteger(double val)
{
int truncated = (int)val;
return (val == truncated);
}
int main(int argc, char *argv[])
{
//local variable
double a, b;
char operation, option = 'y';
//loop
while(option == 'y' || option == 'Y')
{
//system("cls");
printf("Enter number and operator to solve:\n\nExapmple [a + b][a - b][a * b][a / b]\n");
scanf("%lf %c %lf", &a, &operation, &b);
// nested if
if(isInteger(a) && isInteger(b))
{
if(operation == '+')
{
printf("Result: %.1lf\n\n", a + b); //ouput result
}
else if(operation == '-')
{
printf("Result: %.1lf\n\n", a - b); //ouput result
}
else if(operation == '*')
{
printf("Result: %.1lf\n\n", a * b); //ouput result
}
else if(operation == '/')
{
printf("Result: %.1lf\n\n", a / b); //ouput result
}
else
{
//output error
printf("Invalid Operater!\n");
}
}
else
{
//output error
printf("Input is not a digit!\n");
}
//output selection
printf("Do you want to retry [y]/[n]?");
option = getch(); //not recommended but just a small project
//scanf("%c", &option); -- stops the loop
} //end loop
}
解决方案
在你的第二个例子中(即第二次),这条线
scanf("%lf %c %lf", &a, &operation, &b);
尝试将a读入 double ,这将导致scanf
失败并提前返回。
检查文档,scanf
您会看到它返回读取的值的数量,并将errno
在失败时设置。这些必须在之前检查a
,operation
并且b
可以安全使用。
推荐阅读
- javascript - Vue.js 对话框/模态在父组件上关闭
- python - 如何解决此错误:“RefVariable”对象不支持项目分配?
- c# - 如何正确保护忘记密码的端点
- r - 如何计算一个自变量的最优数量以获得最小的模型输出?
- r - 将一个函数积分到 R 中的另一个积分上
- database - 通过添加和删除保持键值用例的顺序
- css - 难以将 Bootstrap 自定义复选框向右对齐
- java - onStop() 在线状态问题 - 主屏幕与以前的活动
- java - 我们如何使用 KLOV(Extent Reports) 向 MongoDB AWS 发送信息?
- c# - C# 使用 ^ 符号时如何反转模数