c/c++语言开发共享在整数中获取double值的小数部分而不会丢失精度

我想将double值的小数部分转换为精度,最多4位数转换为整数。 但是当我这样做时,我会失去精确度。 有什么方法可以让我获得精确的价值吗?

#include int main() { double number; double fractional_part; int output; number = 1.1234; fractional_part = number-(int)number; fractional_part = fractional_part*10000.0; printf("%lfn",fractional_part); output = (int)fractional_part; printf("%dn",output); return 0; } 

我期待输出为1234但它给出1233.请建议一种方式,以便我可以获得所需的输出。 我想用C语言的解决方案。

    假设你想要得到一个正分数,即使是负值,我也会选择

     (int)round(fabs(value - trunc(value)) * 1e4) 

    哪个应该给你预期的结果1234

    如果你不圆,只是截断值

     (int)(fabs(value - trunc(value)) * 1e4) 

    (这与原始代码基本相同),您将以双精度最终得到意外结果12331.1234 - 1.0 = 0.12339999999999995

    如果不使用round() ,如果将操作顺序更改为,也会得到预期的结果

     (int)(fabs(value * 1e4 - trunc(value) * 1e4)) 

    如果value的整数部分足够大,浮点不准确性当然会再次启动。

    你可以使用modf()而不是像David建议的那样使用trunc() ,这可能是浮点精度的最佳方法:

     double dummy; (int)round(fabs(modf(value, &dummy)) * 1e4) 

    数= 1.1234,整数= 1,分数= 1234

     int main() { double number; int whole, fraction; number = 1.1234; whole= (int)number; fraction =(int)(number*10000); fraction = fraction-(whole *10000); printf("%dn",fraction); printf("%dn",whole); return 0; } 

    任何数字的解决方案可以是:

     #include  using namespace std; int _tmain(int argc, _TCHAR* argv[]) { float number = 123.46244; float number_final; float temp = number; // keep the number in a temporary variable int temp2 = 1; // keep the length of the fractional part while (fmod(temp, 10) !=0) // find the length of the fractional part { temp = temp*10; temp2 *= 10; } temp /= 10; // in tins step our number is lile this xxxx0 temp2 /= 10; number_final = fmod(temp, temp2); cout< 

    使用modf和ceil

     #include  #include  int main(void) { double param, fractpart, intpart; int output; param = 1.1234; fractpart = modf(param , &intpart); output = (int)(ceil(fractpart * 10000)); printf("%dn", output); return 0; } 

      以上就是c/c++开发分享在整数中获取double值的小数部分而不会丢失精度相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/559722.html

      (0)
      上一篇 2021年1月27日
      下一篇 2021年1月27日

      精彩推荐