简体   繁体   中英

conversion from float to integer

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

^ 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 .

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.

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

^是按位异或运算符,即编译器为何给出警告。请尝试使用math.h头文件中声明的pow函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM