c++识别输入值为0
C++ recognising input value of 0
我在一段代码上遇到了一点麻烦,想问一下是否可以得到一些帮助。基本上,我正在创建一个程序,该程序将划分用户输入的两个数字,如果输入的数字中的任何一个是0,我想打印一条消息,但是,这部分代码不能正常工作。下面是我的代码:
int main()
{
float n1 = 0.0, n2 = 0.0, quotent = 0.0;
int firstNumberRead = 0;
int secondNumberRead = 0;
firstNumberRead = scanf("%f", &n1);
secondNumberRead = scanf("%f", &n2);
//check that the attempt to read the number was successful
if (firstNumberRead && secondNumberRead == 1)
{
//divide the first number by the second number
quotent = (n1 / n2);
//print quotent
printf("%f", quotent);enter code here
}
else if (firstNumberRead || secondNumberRead == 0)
{
printf("invalid input - divide by zero is not allowed");
}
else
{
printf("invalid input");
}
scanf("%f", &n1);
return (0);
}
这段代码有很多问题。
if (firstNumberRead && secondNumberRead == 1)
你可能误解了c++中的条件是如何工作的,查看你的教科书以获得详细的解释。你很可能想说
if(firstNumberRead == 1 && secondNumberRead == 1)
这将只检查两个scanf
调用是否设法读取一个值。您需要在if
表达式中检查实际值。
另一个问题是检查了分母和分子中0
的不正确变量(您再次检查了firstNumberRead
和secondNumberRead
)。你应该检查n1
和n2
:
if (n1 == 0 || n2 == 0)
通常对浮点变量使用==
运算符是一个坏主意,但是你可以认为它对分母是有意义的(从算术的角度来看,所有其他状态都是合法的)。但是你可能想看看std::abs
看看它是否比某个小。例如:
if (abs(n1) < 0.001 || abs(n2) < 0.001)
最后,您可能想要这样做:
if (firstNumberRead == 1 && secondNumberRead == 1)
{
if (n1 == 0 || n2 == 0)
{
printf("invalid input - divide by zero is not allowed");
}
else
{
//divide the first number by the second number
quotent = (n1 / n2);
//print quotent
printf("%f", quotent);
}
}
else
{
printf("invalid input");
}
相关文章:
- Bison/flex 在识别规则后等待输入
- 静态堆栈函数不会 1) 输入第一个元素 2)添加新元素时识别旧元素
- 函数的函数无法识别输入参数
- 为什么 IDE 无法识别我的输入?
- TensorFlow模型:如何从原始爱好文件中识别输入/输出节点名称
- 为什么输入流无法识别 Ctrl D 并给出无限循环
- 如何识别输入的输入字符串在 c++ 中是两个还是多个单词
- 为什么此代码只能识别文本文件中的第一行?输入任何大于 1 的数字都会返回"Atomic Number Not Found"
- 如何在控制台应用程序中使用GetMessage()使用Windows API识别C++中的键盘输入
- 无法识别键盘输入
- 程序输入只识别单词而不识别行
- 如何识别.exe文件是否需要输入参数
- c++getline似乎无法识别通过管道传输到stdin的输入中的换行符
- 如何识别输入组合
- 检测键盘输入后,窗口识别的关键
- 使字符数组在输入时识别空格
- 接受并识别任何类型的c++输入
- c++识别输入值为0
- 如果语句不工作,输入无法识别(c++)
- 无法弄清楚为什么我的开关不工作。似乎无法识别 cin 输入