Hi everyone!
Today, I found some problems while trying to print a double values in C++. Below is my code:
#include<bits/stdc++.h>
using namespace std;
int main(void) {
double x=1.0/3000;
printf("%.7lf\n",x);
return 0;
}
When I compile this code using command mingw32-g++.exe -O2 -Wl,--stack=268435456 -DSKY
, I saw 0.0003333
. However, after changed to mingw32-g++.exe -O2 -std=c++11 -Wl,--stack=268435456 -DSKY
(include C++11), I saw 0.0000000
.
I uss Windows 8 and my g++ version is:
C:\Program Files (x86)\CodeBlocks\MinGW\bin>"mingw32-g++.exe" --version
mingw32-g++.exe (tdm-1) 4.7.1
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Has anyone ever met this problem? What is the solution to avoid this?
I'm looking forward to your answers. Thank you :D
cout works fine
Have you also tried %f ?
All these double type printing is very confusing in C++. You can see this question on Stackoverflow:
This is C99 standard. Finding what is the current standard requires some more efforts, so I'll stop here. Anw, moral of the story is trying your best to avoid printf, scanf when dealing with floating types.
No g++, no problems. MS C++ works fine.
C++ standard = no problems.
http://stackoverflow.com/questions/4264127/correct-format-specifier-for-double-in-printf
(Ok, I_love_Hoang_Yen already gave this link. Also there is no guarantee that new MSVC will support lf for doubles)
I use %lf without any problems. I see many C++-coders who use %lf without any problems, too. Recently, I use cout and I notice that the running time is almost the same. Thus, I think cout may be the solution for you.
If you're using mingw with c++11 support, use
%f
forprintf
,%lf
forscanf
.Comments about following standard are irrelevant because Windows doesn't anyway.
cout<<fixed<<setprecision(10); and you can forget what is f, lf, Lf or maybe lF, LF and shit. Moreover no longer any problems with stupid 0.000000
Unless you printing fkn long double on fkn mingw at NEERC
Is this a case in both iostream and cstdio? I recall one contest in gym when my team got one task accepted after contest and only needed change was to print double instead of long double, however I don't remember whether we were using iostream or cstdio.
Well, I believe with both.
As far as I remember problem is that version of MinGW used input/output from MS libraries which doesn't have functions for printing long double(which is equal to double in MSVC)
I would strongly recommend to use this version of printf on Windows: http://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/ By default printf(and scanf) on Win32 is something very strange and non-standard
It's ten times slower (not kidding) than 'standard'
printf
, isn't it?By the way, the page says that problem happens on Windows XP or earlier, which should already be buried.