Question

it's my first day messing around with C++. I'm trying to do just a really basic code looking for the roots in a quadratic equation. Here is my code so far:

#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;
    }

I'm getting this error:

invalid operands to binary expression ('double' and 'double (*)(const char *)')

in the line:

if (root1 && root2 != nan) 

I'm looking for a simple test to see if the roots exist and this obviously doesn't work. Thanks in advance for your help!

Was it helpful?

Solution

To check if something is a real number, use isnan:

if(!isnan(root1) && !isnan(root2)) 

Explanation:

isnan determines if the given floating point number arg is not-a-number (NaN). It returns true if arg is NaN, false otherwise.

The NaN values are used to identify undefined or non-representable values for floating-point elements, such as the square root of negative numbers or the result of 0/0. In C++, it is implemented with function overloads for each floating-point type, each returning a bool value.

OTHER TIPS

double (*)(const char *) is a type which represents a pointer to a function that returns a double and takes a const char * argument. You'll find if you look at a reference for cmath that nan is the function in question.

Looks like you should be able to call it with an empty string to get a suitable value:

nan("")

However, you can't provide a double on one side of && and a bool on the other, so you'll need to have a suitable test for root1 as well.

And yes, that type syntax for nan is a bit crazy, that's how C does function pointer syntax, and the name of a function by itself represents a pointer to it, so that's what you get out of the compiler because C++ inherited C-style function pointers.

Use (C++11):

#include <cmath>
...
if (!isnan(root1) && !isnan(root2)) 

Use if (root1 != nan("") && root2 != nan(""))

The problem is in two places:

  1. root1 is always true except when it is 0
  2. nan is not declared, it should be nan("")

But I think it is better to use !isnan(root1) instead of just nan

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top