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!

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

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