c ++ builder FloatToStr()bug

时间:2013-06-03 04:23:46

标签: c++ c++builder

我使用FloatToStr()但它有错误! 我告诉你我的酸性代码。

void __fastcall TForm1::FormCreate(TObject *Sender)
{ 
float i=3.14;
 Double j=3.14;
 Double k=0;
 Double m,n;

 Edit1->Text=FloatToStr(i);         //  It's show 3.14000010490417
 Edit2->Text=FloatToStr(j);         //  It's show 3.14

 Edit3->Text=FloatToStr(314/100);   // It's  show 3

 k=314/100;
 Edit4->Text=FloatToStr(k);         // It's show  3

 m=314;
 n=100;
 Edit5->Text=FloatToStr(m/n);       // It's  show 3.14

}
我问?为什么?所有都不显示3.14 ???? !或者它是FloatToStr()中的错误!!

  1. Edit1->文字= FloatToStr(ⅰ); //它显示3.14000010490417
  2. Edit3->文字= FloatToStr(一百分之三百十四); //这是节目3
  3. Edit4->文字= FloatToStr(K); //这是节目3
  4. 感谢回答。

3 个答案:

答案 0 :(得分:2)

您得到的结果不同,因为您在代码中将整数除法与浮点除法混合在一起。 整数除法会截断小数点后的所有内容

// This line is performing integer division
// and the final result is passed into FloatToStr.
// aka it's the same as calling FloatToStr(3).
Edit3->Text=FloatToStr(314/100);

// Again, the right-hand side is doing integer division
// and the result is implicitly casted to a double.
// aka it's the same as doing k = static_cast<double> (3);
k = 314/100;
Edit4->Text=FloatToStr(k);         // It's show  3

// These two lines implicitly casts int to a double
// when assigned in this manner.
m = 314;
n = 100;
// Now this is performing double division so you 
// get the expected result. It's the same as calling
// Edit5->Text=FloatToStr( 314.0/100.0 );
Edit5->Text=FloatToStr(m/n);       // It's  show 3.14

答案 1 :(得分:0)

为什么浮点数不能完全保持3.14的问题是计算机中的所有数字都存储在二进制代码中,用十进制代码编写的浮点数不能完全转换为二进制代码。

数字写在更大的位上是一个更好的近似值。


查找

http://docwiki.embarcadero.com/RADStudio/XE4/en/Internal_Representation_Of_Numerical_Types

long double(C ++)= Extended(Delphi,Builder)

number = <Significand> * 2^<Biased_exponent>
    // (there's also the sign bit, etc.)

<Biased_exponent>不是10的强弱,所以很难获得良好的近似值。


另一个帮助文档:

http://docwiki.embarcadero.com/RADStudio/XE4/en/Constants_And_Internal_Representation


编辑:

当然问题在于分工:

int / int = int        
double / int = double

答案 2 :(得分:0)

表达式314/100会产生一个整数,因为您要划分2个整数值。如果要使用浮点运算进行除法,则应使用表达式314.0 / 100.0

在代码中使用静态数字中的小数点分隔符(。)使编译器将其用作浮点值。