Please include a minimum working example with your code.
Anyway, it works on my system (Debian GNU/Linux testing, gcc 5.2.1):
#include <math.h>
#include <stdio.h>
int main() {
float a,b,c;
scanf("%f",&a);
scanf("%f",&b);
scanf("%f",&c);
if ((pow(b,2.0)-4*a*c)<0)
printf("\nNo roots!\n");
else if((pow(b,2.0)-4*a*c)>0) {
printf("\nRoots=%.2f and %.2f\n",
(-b+pow(b*b-4*a*c,0.5))/(2*a),
(-b-pow(b*b-4*a*c,0.5))/(2*a));
} else
printf("\nBoth roots are %.2f\n",-b/(2*a));
return 0;
}
If I enter 1, 14, 49, the program answers Both roots are -7.0
. But this may vary among systems, because you are using floating point arithmetic and I don't know how your pow()
function was implemented. Not all real numbers can be represented on a computer -- here's a good description of how it works for single precision floats. And each compiler/runtime environment will have a possibly different implementation of the math library (which includes pow
, that you have used).
So, I would avoid pow
at all if possible. Use b*b
instead, and save pow
for when you really need it. And as Tom Karzes mentioned, sqrt
is also better than using pow
for calculating square roots.
One last thing: calculating the discriminant only once would make your program more readable:
#include <math.h>
#include <stdio.h>
int main() {
float a,b,c;
float delta;
scanf("%f",&a);
scanf("%f",&b);
scanf("%f",&c);
delta = b*b-4*a*c;
if (delta<0)
printf("\nNo roots!\n");
else if(delta>0)
printf("\nRoots=%.2f and %.2f\n",
(-b+sqrt(delta))/(2*a),
(-b-sqrt(delta))/(2*a));
else
printf("\nBoth roots are %.2f\n",-b/(2*a));
return 0;
}
One more thing you may try is to use double
instead of float
, so you'll have more precision (not relevant depending on the numbers you'll be using, but it's a good idea to use doubles
if you don't have huge matrices of numbers that could take too much memory -- a double
takes twice as memory as a float
to represent).