Handling doubles with large integer parts in C++

冷暖自知 提交于 2019-12-12 04:56:27

问题


I need to handle sub-metre coordinates in C++ which have large integer parts (e.g. 515876.12 // 5117789.22), but I'm having issues with rounding:

double inUTMX = 560351.12 is displayed as 560351
double inUTMY = 5113570.22 is displayed as 5.11357e+06

I can normalise the coordinates for processing if necessary (e.g. /1e5), but I need to read-in the sub-metre coordinates via command line in the first place. Trouble is they always get rounded.

Is there a neat way to deal with doubles that have large integer values in C++?

(Tried it in Python it stores the entire precision fine as a float, just wondering where I'm going wrong.)

Any ideas / pointers much appreciated.


回答1:


You can modify how doubles are streamed by using std::setprecision.

Example:

#include <iostream>
#include <iomanip>

int main () {
   double inUTMX = 560351.12;
   double inUTMY = 5113570.22;

   std::cout << std::setprecision(20) << inUTMX << std::endl;
   std::cout << std::setprecision(20) << inUTMY << std::endl;

  return 0;
}

Output:

560351.11999999999534
5113570.2199999997392


来源:https://stackoverflow.com/questions/29709166/handling-doubles-with-large-integer-parts-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!