-2

I'm trying to cast 2 integers into floats using static_cast. The problem is that when I do the math I get 4 instead of 4.00.

Below I have made an example of the code.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    int num = 4,
        den = 1;

    cout << static_cast<float>(num) / static_cast<float>(den);
}

If I'm doing it incorrectly,then please indicate where i am wrong. Also please mention if there is a way to get 4.00 instead of just 4?

hmishra2250
  • 54
  • 1
  • 10
  • http://stackoverflow.com/questions/14677448/how-to-cout-a-float-number-with-n-decimal-places – Nathan Cooper Oct 24 '15 at 11:59
  • 2
    Possible duplicate of [How do I print a double value with full precision using cout?](http://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout) – Eelke Oct 24 '15 at 12:01
  • 1
    What is the difference between 4.00 and 4? That said, in order to avoid those useless casts, create float literals: `float num = 4.0f;`. As a general rule, whenever you feel the temptation to add a cast to make code compile or to make it compile without warnings, you have been using the wrong type to begin with. – Ulrich Eckhardt Oct 24 '15 at 12:31
  • `4.00`, `4`, and `four`, are just different representations of the same value. When you divide two numbers, you get a value. – David Schwartz Oct 24 '15 at 12:44

1 Answers1

3

Combining what is written by Nathan and Eelke, use the Floating point Format flag fixed along with setprecision Parametric manipulator, available in iomanip library.
Here is what your code look likes, after required changes :`

#include <iostream>
#include <iomanip>

int main()
{
    int num = 4,
    den = 1;
    std::cout << std::fixed << std::setprecision(2) << 
            static_cast<float>(num) / static_cast<float>(den);
    return 0;
}
Jive Dadson
  • 16,680
  • 9
  • 52
  • 65
hmishra2250
  • 54
  • 1
  • 10