简体   繁体   English

从浮点数到整数的转换

[英]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 当我输入-6和9时,它得出的根数是6和0,这当然是不正确的,请帮助我

^ 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 ). 要将数字提升为任意幂,请使用std::pow (来自标准标头cmath )。 For powers of two, you can just use x * x . 对于2的幂,可以只使用x * x

b^2 means to use the XOR operator, which I don't think is what you meant to use. b ^ 2表示使用XOR运算符,我认为这不是您要使用的运算符。 Try using b*b. 尝试使用b * b。 Also it might be helpful to declare a, b, and c as floats and not ints. 同样,将a,b和c声明为float而不是ints可能会有所帮助。

besides the correct remarks on the xor operation 除了关于异或运算的正确说明

you cannot do all the calculations on int and then cast it to float. 您不能对int进行所有计算,然后将其强制转换为float。 this way the div result is rounded. 这样,div结果将被四舍五入。 try to cast b in the middle of the calculation like (float)b. 尝试像计算(float)b一样在计算中间投射b。 or define all a,b,c and d as floats 或将所有a,b,c和d定义为浮点数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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