One of the functions I'm struggling with to write?


This is one of the functions I'm struggling with to write and I don't get please help me so I can understand this here is the question

Write a C++ function named quadratic which has parameters a,b, and c of type int which calculates only double real roots of quadratic equations according to the formula:

r1=-b+Sqrt(b^2-4ac)/(2a)), r2=-b- Sqrt(b^2-4ac)/(2a))

The two real roots are passed back to the caller via two parameters r1 and r2 of type float. When quadratic cannot calculate two real roots, it prints out the appropriate error message and returns -1 to the caller as a warning not to use the values of the roots. When it can calculate two real solutions, it returns 1 to the caller to indicate success.(better picture below of quadratic equation)
check my code below and tell me whats wrong
#include <iostream>
#include <cmath>
using namespace std;

int quadratic(int a, int b, int c, double &r1, double &r2);
int main()
{
double r1, r2;
r1 = r2 = 0.0;
if (quadratic(2,5,3, r1, r2)>0)
cout << "r1: " <<r1 <<"\tr2: "<<r2<<endl;
return 0;
}

int quadratic(int a, int b, int c, double &r1, double &r2){
if(pow(b,2)-4*a*c < 0){
cout << "Non real result"<<endl;
return -1;
}
else{
r1= (-b + sqrt(pow(b,2) - 4*a*c)) /(2*a);
r2= (-b - sqrt(pow(b,2) - 4*a*c)) /(2*a);
return 1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int quadratic(int a, int b, int c, double &r1, double &r2)
{
    if(pow(b,2)-4*a*c < 0)
    {
        cout << "Non real result"<<endl;
        return -1;
    }
    else
    {
        r1= (-b + sqrt( pow(b,2) - 4*a*c)) /(2*a);

        r2= (-b - sqrt(pow(b,2) - 4*a*c)) /(2*a);
        return 1;
    }
}


I think that's what you already have anyway.

EDIT:
See vlad from moscow post below - about use of float rather than double - I should have read the text more closely
Last edited on
In your assignment there is writtten that parameters r1 and r2 shall have type float. Below is a realization of the function


1
2
3
4
5
6
7
8
9
10
11
12
13
14
int quadratic( int a, int b, int c, float &r1, float &r2 )
{
	if ( b * b - 4 * a * c < 0 )
	{
		std::cout << "Non real result" << std::endl;
		return -1;
	}
	else
	{
		r1 = ( -b + std::sqrt( b * b - 4.0f * a * c ) ) / ( 2.0f * a );
		r2 = ( -b - std::sqrt( b * b - 4.0f * a * c ) ) / ( 2.0f * a );
		return 1;
	}
}
Topic archived. No new replies allowed.