我在处理一段代码时遇到了一些麻烦,想问问我是否可以获得一些帮助。基本上我正在创建一个程序,它将划分用户输入的两个数字,如果输入的数字中的任何一个为 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
并检查它是否小于某个 epsilon。例如:
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");
}
关于C++ 识别输入值 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40053906/