I have a C++ program that runs on both Windows/Linux. On Windows the program is compiled with Visual Studio 2012 and Linux it is compiled with GCC. When converting doubles to strings using sprintf Visual Studio is using a different rounding method than the GCC compiler for ties - ie decimals ending in a 5.
Visual Studio compiler appears to perform round half away from zero while GCC does round even aka bankers rounding.
Round even is the desired behavior.
Is it possible to change the rounding behavior used for sprintf format strings in visual studio / windows? As I need to make the rounding behave consistently between the two.
Here is a small sample C++ program that illustrates the above described behavior:
int main()
{
char buffer[100];
double x;
for (x = -0.5; x <= 10.5; x += 1.0)
{
sprintf(buffer,"%4g %.0f
", x, x);
std::cout << buffer;
}
return 0;
}
Windows output. Numbers are rounded away from zero:
OSX output compiled using xCode. Numbers are rounded using round even towards the even number:
OSX output:
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…