C++ data types | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

C++ data types

In the following code, whether I use a float or double, I get the same number as a result. Shouldn't the double, display a number with more digits after the decimal point???? I used for example the number 3.111111 with six "1s" and it still outputs the number 3.11111 with five "1s", as the float did... #include <iostream> using namespace std; int main() { double a; cin >> a; cout << a; }

4th Sep 2017, 6:55 PM
Christos Provopoulos
14 Answers
+ 7
You need to use setprecision() on the cout object. http://www.cplusplus.com/reference/iomanip/setprecision/ ex: std::setprecision(numberofdigits);
4th Sep 2017, 6:57 PM
Karl T.
Karl T. - avatar
4th Sep 2017, 6:58 PM
Manual
Manual - avatar
+ 6
Calculations in double are more precise but to output the result with a given number of digits you need to precise it....
4th Sep 2017, 7:02 PM
Karl T.
Karl T. - avatar
+ 6
Yes. You need to format the output.
4th Sep 2017, 7:15 PM
Karl T.
Karl T. - avatar
+ 5
Each Data type in C++ such a number types int, double , float, long double, have ranges.
4th Sep 2017, 6:59 PM
Manual
Manual - avatar
+ 5
double will not display extra zeros eg 14.0 - float would display the zero though
4th Sep 2017, 7:02 PM
Manual
Manual - avatar
+ 5
if you want a variable to have a certain amount of digits used the right data type for the job
4th Sep 2017, 7:04 PM
Manual
Manual - avatar
+ 5
@Christos if you give the value long (long doub) 12.0001 that number will be displayed if you give 12.000 double will ignore the zeros and output 12
4th Sep 2017, 7:17 PM
Manual
Manual - avatar
4th Sep 2017, 7:29 PM
Manual
Manual - avatar
+ 3
My mistake that code takes the remainer of what is not covered in a data type. max ranger if no value for a range
4th Sep 2017, 7:32 PM
Manual
Manual - avatar
+ 1
@manual Actually the same happens with float
4th Sep 2017, 7:24 PM
Christos Provopoulos
0
So this should be used only on the cout object? If i use the input as a value for the rest of the program, for calculations etc., It would use the number initially given??
4th Sep 2017, 7:00 PM
Christos Provopoulos
0
@Manual That's the reason I used the double; to increase the range...
4th Sep 2017, 7:06 PM
Christos Provopoulos
0
@Karl T. So the program will use the given value but can't print it without the precision???
4th Sep 2017, 7:07 PM
Christos Provopoulos