Блог пользователя I_love_tigersugar

Автор I_love_tigersugar, 11 лет назад, По-английски

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

  • Проголосовать: нравится
  • +29
  • Проголосовать: не нравится

»
11 лет назад, скрыть # |
 
Проголосовать: нравится -33 Проголосовать: не нравится

cout works fine

»
11 лет назад, скрыть # |
 
Проголосовать: нравится +52 Проголосовать: не нравится

Have you also tried %f ?

All these double type printing is very confusing in C++. You can see this question on Stackoverflow:

  • for scanf: %f is float, %lf is double, %Lf is long double
  • for printf: %f is double, %Lf is long double.

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.

»
11 лет назад, скрыть # |
 
Проголосовать: нравится -54 Проголосовать: не нравится

No g++, no problems. MS C++ works fine.

»
11 лет назад, скрыть # |
 
Проголосовать: нравится -10 Проголосовать: не нравится

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.

»
11 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

If you're using mingw with c++11 support, use %f for printf, %lf for scanf.

Comments about following standard are irrelevant because Windows doesn't anyway.

»
11 лет назад, скрыть # |
 
Проголосовать: нравится +8 Проголосовать: не нравится

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

»
11 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

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