quadratic equation passing values to a function

Mar 21, 2014 at 2:23pm
Hi,

I've been trying the below code and it's not giving the correct results. I'd like help with it.

Thanks.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
  # include<iostream>
# include<cmath>
using namespace std;
void getValues(double &a, double &b, double &c);
double calculate();
void display();

void getValues(double &a, double &b, double &c)
{
			
	cout<<"Enter the coefficient a"<<endl;
	cin>>a;
	cout<<"Enter the coefficient b"<<endl;
	cin>>b;	
	cout<<"Enter the coefficient c"<<endl;
	cin>>c;
}

double calculate()
{

	double a, b, c, d, x;
	
	x = (b * b) - (4 * a * c);
	d = sqrt (x);
	
	if(d < 0){
		cout<<"There are no real roots"<<endl;
	}			
	else if(d > 0){
		cout<<"Root 1 is "<<-b+sqrt(d)/(2*a)<<" Root 2 is "<<-b-sqrt(d)/(2*a);		
	}			
	else{
		cout<<"There is one equal root "<<(-b+d)/2*a;
	}
				
		
}

int main()
{
	double a, b, c;
	
	getValues(a, b, c);
	calculate();		
	return 0;
}
Mar 21, 2014 at 2:38pm
it's not giving the correct results

It doesn't even compile on my box.

e.g. you're telling calculate to return a double, but your function does not return anything.

leaving that aside though...
1
2
3
	double a, b, c, d, x;

	x = (b * b) - (4 * a * c);


what do you think x will be calculated to, considering you haven't initialised a, b or c..?

remove the declarions for a,b and c in this function, and have them be passed in.

Last edited on Mar 21, 2014 at 2:45pm
Mar 21, 2014 at 2:52pm
You haven't passed any values to the calculate function, you need to pass the values you got by reference to calculate such as,

calculate(a,b,c);

Also when you say,

if(d < 0){

Well you should be saying,

if (x < 0)

as you have already taken sqrt of x.
Mar 21, 2014 at 4:47pm
Thanks guys for the assistance. I've managed to fix the issues you pointed out and it's now working.
Topic archived. No new replies allowed.