I have a simple C++ program that I thought would print out a double value defined in f and g as doubles ... but C++ is printing them out as integers. I checked the default precision of cout, and when I run it the output says the default precision should be 6 so I'm confused as to why the double isn't printing properly.
#include <iostream>
#include <stdio.h>
int main() {
double f = 735416.416898;
double g = f + 0.3;
std::cout << "default precision is " << std::cout.precision() << std::endl;
std::cout << "[c++] f = " << f << std::endl;
std::cout << "[c++] g = " << g << std::endl;
printf("[c] f = %f\n", f);
printf("[c] g = %f\n", g);
f = 735416.516898;
g = f + 0.3;
std::cout << "[c++] f = " << f << std::endl;
std::cout << "[c++] g = " << g << std::endl;
printf("[c] f = %f\n", f);
printf("[c] g = %f\n", g);
return 0;
}
The output I'm seeing is:
kiran@kiran-VirtualBox:~/test$ g++ -o test test.cpp
kiran@kiran-VirtualBox:~/test$ ./test
[c++] f = 735416
[c++] g = 735417
[c] f = 735416.416898
[c] g = 735416.716898
[c++] f = 735417
[c++] g = 735417
[c] f = 735416.516898
[c] g = 735416.816898
Because the default precision is showing up as 6, shouldn't the cout also be showing the 6 decimal places?
If I do
std::cout << std::fixed << f
it prints properly (w/ all the decimal places).
Just wondering if someone can explain this behavior to me? Is it expected? Am I expected to use std::fixed to force printing of doubles properly?