jeudi 11 janvier 2018

C++ : How to use a pointer in an if statement condition

I am writing a program that takes in 3 user inputted values for a quadratic equation, does some calculation, and returns how many roots the quadratic has.

When I print *(point), it gives me the correct value from the function.

However, when I use *(point) in the If conditions, it does not seem to work the way I want it to - I believe that *(point)is always some positive number, hence why it always executing that specific if condition.

The user values: a = 9, b = -12, c = 4 should print out This quadratic has 1 root. and the values: a = 2, b = 16, c = 33 should print out This quadratic has 2 roots. BUT the program always prints out This quadratic has 0 roots. no matter what the values entered.

Here is my code:

#include "stdafx.h"
#include <iostream>

using namespace std;

float *quadratic(float a1[]);

int main()
{

    float a1[3] = {};
    float *point;

    cout << "Enter a: ";
    cin >> a1[0];
    cout << "\nEnter b: ";
    cin >> a1[1];
    cout << "\nEnter c: ";
    cin >> a1[2];

    point = quadratic(a1);

    cout << endl << "d = " << *(point) << endl; 

    if (*(point) < 0) {
        cout << "\nThis quadratic has 2 roots.\n";
    }
    else if (*(point) > 0) {
        cout << "\nThis quadratic has 0 roots.\n";
    }
    else { //else if *(point) is equal to 0
        cout << "\nThis quadratic has 1 root.\n";
    }

    return 0;
}

float *quadratic(float a1[]) {

    float d;
    d = (a1[1] * a1[1]) - (4 * a1[0] * a1[2]);

    float xyz[1] = { d };
    return xyz;

}

Aucun commentaire:

Enregistrer un commentaire