Trouble with quadratic equation

Hi I am trying to create a basic program to calculate the roots of a quadratic equation, but my compiler tells me that the operand double is illegal. What am I doing wrong? I am using Microsoft visual studio express 2012.

If I wrote the same code with int variables the program will compile and run, but will give wrong answers!

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
#include "stdafx.h"
#include <stdio.h>

int main()
{
double a;
double b; 
double c;
double d;
double e;

printf("Input a value for a: ");
scanf_s("%lf",&a);

printf("\nInput a value for b: ");
scanf_s("%lf",&b);

printf("\nInput a value for c: ");
scanf_s("%lf",&c);

d = (-b+(b^2-4*a*c)^(1/2))/2*a;
e = (-b-(b^2-4*a*c)^(1/2))/2*a;

printf("\nRoots of the equation y = %lfx^2 + %lf*x + %lf are %lf and %lf\n",a, b, c, d, e);
}
There isn't an operator in c / c++ to raise a number to a power.
In this case, use the sqrt() function. More generally, use pow()
It's simpler to use b*b rather than pow(b, 2.0).
http://www.cplusplus.com/reference/cmath/sqrt/
http://www.cplusplus.com/reference/cmath/pow/

By the way, this d = (something)/2*a means something divided by 2 then multiplied by a. You want the 2 * a to be done before the division, so put it in parentheses.
Last edited on
Excellent thank you! My program now works as intended.

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
#include "stdafx.h"
#include <stdio.h>
#include <math.h>

int main()
{
double a;
double b; 
double c;
double d;
double e;

printf("Input a value for a: ");
scanf_s("%lf",&a);

printf("\nInput a value for b: ");
scanf_s("%lf",&b);

printf("\nInput a value for c: ");
scanf_s("%lf",&c);

if ((pow(b,2)-4*a*c)<0)
{
	printf("\nRoots are imaginry\n\n");
}
else
	{
	d = (-b+sqrt(pow(b,2)-4*a*c))/(2*a);
	e = (-b-sqrt(pow(b,2)-4*a*c))/(2*a);
	printf("\nRoots of the equation y = %lfx^2 + %lf*x + %lf are %lf and %lf\n",a, b, c, d, e);
}
}
Topic archived. No new replies allowed.