1

I have written the code as follows

#include <stdio.h>

int main()
{
    long double var = 3.1415926535;
    printf("%.6Lf", var);
}

The output of the code is 0.000000. According to me output should be 3.141592. Please tell what mistake I am doing.

  • 1
    It's going to be very hard to replicate the problem since the code is correct. Are you sure you build the exact code you show? How do you build it? In what environment? What compiler (name and version)? – Some programmer dude Aug 19 '21 at 07:58
  • I have compiled the code using code::blocks ide as well as using VS code (with gcc compiler) on windows OS. – Harshit Singh Aug 19 '21 at 08:00
  • 1
    Quibble: output should be `3.141593` (last digit is rounded). – Weather Vane Aug 19 '21 at 08:00
  • How did you compile the code? What compiler? What compiler options? Where are you running it (PC, phone, key fob,..., *Klingon emulator*)? – pmg Aug 19 '21 at 08:06
  • I have compiled the code using code::blocks ide (GNU GCC compiler) on windows OS in my laptop. – Harshit Singh Aug 19 '21 at 08:08
  • 2
    Try his: `printf("version %s %s -- %.6Lf\n", __DATE__, __TIME__, var);` and check if the version you are running is effectively the version you compiled (date and time of a few seconds ago). – pmg Aug 19 '21 at 08:12
  • 5
    This question was answered in: https://stackoverflow.com/questions/4089174/printf-and-long-double – Fausto Sánchez Hoya Aug 19 '21 at 08:12
  • 2
    @pmg it is showing version Aug 19 2021 13:46:26 -- 0.000000. – Harshit Singh Aug 19 '21 at 08:17
  • 1
    So, my assumption (you running something else other than the result of compiling the code) was wrong. Sorry. Apparently you do have a problem with the interface between compiler (uses `long double`) and library (does not use `long double`). I suggest you stick with plain `double` with your current implementation. – pmg Aug 19 '21 at 08:37
  • @thebusybee No. – Harshit Singh Aug 19 '21 at 09:07
  • 2
    Why not? It is clear the you need to use `__mingw_printf()` since `printf()` uses Microsoft's library that cannot print `long double`s. Read all answers, especially [this one](https://stackoverflow.com/a/14988103/11294831)! – the busybee Aug 19 '21 at 09:40

1 Answers1

-1

Try to use GDB compiler, run your code in steps and see where is the problem and your variable changes its value. This is how we learn program dont expect every time to others to solve your problem, this method must be the last. Take a look at this GDB tutorial and fix this problem at your own.

gregni
  • 417
  • 3
  • 12