How to set number format to show all decimal digits in C++?

c++ variables numbers decimal division

115 观看

1回复

6 作者的声誉

I have a problem in c++, I have this code to do a division:

long a = 33732193487;

int b = 1000000;

double c = (double)a/(double)b;

Well, I would like to store the complete result in the variable c, I mean:

c = 33732.193487;

for later, for example, use this value to make a sum or substrac. But I only get to store the result with one decimal.

Is there any option to store the 6 decimals with c++?

Thank you in advance! Sorry if my question is too obvious.

作者: Carlos Pascual Sanchez 的来源 发布者: 2017 年 12 月 27 日

回应 1


1

62391 作者的声誉

Let me guess (a complete program would have been better): you're seeing six decimal places when you write the value to standard out:

std::cout << c << '\n';

Those six decimal places are the default for output; they have nothing to do with the precision of the value of c, which is determined by the type of c. For double you typically have about fifteen digits. To see those digits in your output statement, use std::setprecision:

std::cout << std::setprecision(15) << c << '\n';

But beware: you can use values greater than 15 in the call to setprecision and the stream inserter will happily generate more digits, with nonsensical values.

作者: Pete Becker 发布者: 2017 年 12 月 27 日
32x32