Reputation:
i have following simpled algorithm for calculation roots of quadratic equation
#include <iostream>
#include <math.h>
using namespace std;
int main(){
float x,x1;
x=0;x1=0;
int a=1;
int b;
int c;
cout<<"enter the second term:"<<endl;
cin>>b;
cout<<"enter the third term:";
cin>>c;
float d=b^2-4*a*c;
if (d<0){
cout<<"the equation has not real solution :"<<endl;
}
else if (d==0) { x=(-b/2); x1=x;}
else
{
x=(-b+sqrt(d))/2;x1=(-b-sqrt(d))/2;
}
cout<<"roots are :"<<x<< " "<<x1<< " "<<endl;
return 0;
}
but it gives me warning
arning C4244: '=' : conversion from 'int' to 'float', possible loss of data
and when i enter -6 and 9 it gives that roots are 6 and zero which of course is not true please help me
Upvotes: 0
Views: 313
Reputation: 816
^ is a bitwise xor operator i.e why the compiler is giving warning.Try using pow function declared in math.h header file.
Upvotes: 1
Reputation: 697
besides the correct remarks on the xor operation
you cannot do all the calculations on int and then cast it to float. this way the div result is rounded. try to cast b in the middle of the calculation like (float)b. or define all a,b,c and d as floats
Upvotes: 2
Reputation: 9492
b^2 means to use the XOR operator, which I don't think is what you meant to use. Try using b*b. Also it might be helpful to declare a, b, and c as floats and not ints.
Upvotes: 3
Reputation: 545488
^
is the bitwise xor operator, not the power, as you probably think. To raise a number to an arbitrary power, use std::pow
(from the standard header cmath
). For powers of two, you can just use x * x
.
Upvotes: 6