c++识别输入值为0

C++ recognising input value of 0

本文关键字:输入 识别 c++      更新时间:2023-10-16

我在一段代码上遇到了一点麻烦,想问一下是否可以得到一些帮助。基本上,我正在创建一个程序,该程序将划分用户输入的两个数字,如果输入的数字中的任何一个是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的不正确变量(您再次检查了firstNumberReadsecondNumberRead)。你应该检查n1n2:

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");
}