0
Float does not show decimals
Hi, In this code I want to make division show no of decimals but despite using float and double it doesnot show it. Also What would I need to do to set fixed no of decimals in code here is the link to the code https://code.sololearn.com/cTFQL93vH9v8
2 Réponses
+ 2
Since `a` and `b` are integer variables, in
div = a / b;
the result of the division is going to be an integer value assigning to a floating point variable. So, for instance, if `a = 5` and `b = 2`, the `5 / 2` is 2 (not 2.5) and then it gets assigned to `div` which implicitly being promoted to `2.0`. Also, the default formatting of the output stream wouldn't bother to include the `.0` (the fraction) part of the value if it is zero. However, the stream can be explicitly informed to handle desired precision if the need arises.
Fix:
cout.precision(3); // set the precision to 3 digits after decimal point
cout << "div is =" << fixed << div << endl; // std::fixed enables the stream to represent the floating point numbers with fixed number of precision
+ 1
Try div = (double)a/b;
div = a/b will calculate a/b first, with a and b being integers -> no decimal places, and assigns the result to div. (double)a/b forces the compiler to calculate with doubled instead of integers