C++基础知识 - 如果语句测试

use*_*758 1 c++ nan

这是我第一天搞乱C++.我正在尝试做一个非常基本的代码,寻找二次方程中的根.到目前为止,这是我的代码:

#include <iostream>
#include <cmath>

int main () {

    int a, b, c;
    double root1, root2;

    std::cout << "Enter the integers a, b, and c to fit in the quadratic equation: ax^2 + bx + c >> " << std::endl;
    std::cout << "a = ";
    std::cin >> a;
    std::cout << "b = ";
    std::cin >> b;
    std::cout << "c = ";
    std::cin >> c;
    std::cout <<"\n";
    std::cout << "Quadratic equation to solve is : " << a << "x^2 + " << b << "x + " << c <<std::endl;

    root1 = (-b + sqrt(b*b - 4*a*c))/(2*a); 
    root2 = (-b - sqrt(b*b - 4*a*c))/(2*a);

    if (root1 && root2 != nan) {
        std::cout << "root 1 = " << root1 << std::endl;
        std::cout << "root 2 = " << root2 << std::endl;
    }
    else 
    std::cout << "no root exists" << std::endl;

    return 0;
    }
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

invalid operands to binary expression ('double' and 'double (*)(const char *)')
Run Code Online (Sandbox Code Playgroud)

在线:

if (root1 && root2 != nan) 
Run Code Online (Sandbox Code Playgroud)

我正在寻找一个简单的测试,看看根是否存在,这显然不起作用.在此先感谢您的帮助!

Rag*_*ull 5

要检查某些内容是否为实数,请使用isnan:

if(!isnan(root1) && !isnan(root2)) 
Run Code Online (Sandbox Code Playgroud)

说明:

isnan确定给定的浮点数arg是否不是数字(NaN).true如果arg是NaN false则返回,否则返回.

NaN值用于标识浮点元素的未定义或不可表示的值,例如负数的平方根或0/0的结果.在C++中,它使用每个浮点类型的函数重载来实现,每个浮点类型返回一个bool值.