C++ 识别输入值 0

标签 c++ input

我在处理一段代码时遇到了一些麻烦,想问问我是否可以获得一些帮助。基本上我正在创建一个程序,它将划分用户输入的两个数字,如果输入的数字中的任何一个为 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并检查它是否小于某个 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/

相关文章:

c++ - 私有(private)变量只需要在构造函数中初始化。如何?

c++ - C:尝试将指针值复制到另一个指针中,出现可修改左值错误

HTML 输入样式 css :focus do not trigger

javascript - 使用 Javascript 对文本区域和输入进行计数

javascript - jQuery 在页面上显示输入的文本

c++ - 运算符的模糊重载>>

C++类函数继承使用从基类继承的另一个类的变量

android - 为什么 clang 将 NULL 定义为 __null?

javascript - INPUT TEXT 删除浏览器默认下拉菜单

javascript - 如何设置 .val() 对输入进行单选检查?