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

20th Jun 2019, 4:53 PM
Huzaifa Imran
Huzaifa Imran - avatar
2 odpowiedzi
+ 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
20th Jun 2019, 5:17 PM
To Seek Glory in Battle is Glorious
To Seek Glory in Battle is Glorious - avatar
+ 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
20th Jun 2019, 5:08 PM
Anna
Anna - avatar