簡體   English   中英

從浮點數到整數的轉換

[英]conversion from float to integer

我有以下簡單的算法來計算二次方程的根

#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;
}

但這給了我警告

arning C4244: '=' : conversion from 'int' to 'float', possible loss of data

當我輸入-6和9時,它得出的根數是6和0,這當然是不正確的,請幫助我

^是您可能認為的按位異或運算符,而不是冪。 要將數字提升為任意冪,請使用std::pow (來自標准標頭cmath )。 對於2的冪,可以只使用x * x

b ^ 2表示使用XOR運算符,我認為這不是您要使用的運算符。 嘗試使用b * b。 同樣,將a,b和c聲明為float而不是ints可能會有所幫助。

除了關於異或運算的正確說明

您不能對int進行所有計算,然后將其強制轉換為float。 這樣,div結果將被四舍五入。 嘗試像計算(float)b一樣在計算中間投射b。 或將所有a,b,c和d定義為浮點數

^是按位異或運算符,即編譯器為何給出警告。請嘗試使用math.h頭文件中聲明的pow函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM