19

Possible Duplicate:
C programming division

probably my question is very simple and stupid. I would like to store the value of a division, in particular 1 / x where x is a integer value.

int x = 17;
double result = 1/x;

I try to do it but I always get 0.000000 ... I try to enter a value fixed in x, for example 1/17 but always get the same value .. what's Wrong?

Community
  • 1
  • 1
Safari
  • 11,437
  • 24
  • 91
  • 191

1 Answers1

33

You are doing integer division.

Try the following and it will work as expected:

int x = 17;
double result = 1.0 / x;

The type of the 1 in the expression you have above is int, and the type of x is int. When you do int / int, you get an int back. You need at least one of the types involved to be floating point (float or double) in order for floating point division to occur.

Unlike in Mathematics, division in C++ can either refer to truncated integer division (what you did) or floating point division (what I did in my example). Be careful of this!

In my example, explicitly what we have is double / int -> double.

Mike Bailey
  • 12,479
  • 14
  • 66
  • 123
  • 7
    Or to make it clear: `double result = (double)1 / x;` – Nobody moving away from SE Feb 26 '12 at 17:23
  • 1
    @Nobody So you mean `double result = 1.0 / x;`? Well, the compiler will do this for you but he might laugh at you for not recognising a double literal yourself. – Christian Rau Feb 26 '12 at 17:53
  • 1
    @Christian Rau It was more of a didactic example to make the automatic type more visible. Of course as a programmer I would always write `1.0` because it is much shorter. – Nobody moving away from SE Feb 26 '12 at 17:55
  • With POD types all mathematical operations are done on parameters of the **same type**. The result type is the same as the input parameters. If the input parameters do not have a matching type then one parameter will be promoted to the type of the other. – Martin York Feb 26 '12 at 19:16