-3
double test3 = 1/7;
NSLog(@"The value of test3 = %1.6f",test3);

Result:

The value of test3 = 0.000000

Why won't it give me a fraction as a float value? It should say:

The value of test3 = 0.142857

What am I doing wrong?

Sparky
  • 172
  • 15

1 Answers1

5

You have to do 1.0 / 7.0 or 1 / 7.0 or 1.0 / 7 for the compiler to do floating point division.

1/7 is simple integer division, which is 0. Only the result of the integer division is casted and stored in test3 and if both arguments are integers then you will get an integer returned.


To include random numbers (as mentioned in the comments):

To generate a random number between an inclusive lower and an exclusive upper bound do this:

int randomNum = lowerBound + arc4random_uniform(upperBound - lowerBound);

Note that one should use arc4random_uniform(x) (thanks rmaddy!) as it is superior to arc4random() % x and rand() % x.

ThreeFx
  • 7,250
  • 1
  • 27
  • 51
  • And I have to do, for example, rand()*1.0/rand()*1.0 in order to get that same effect with two variables. – Sparky Jul 25 '14 at 21:31
  • 1
    @Sparky I'm not sure about that, I would explicitly cast them like this: ``(double)rand() / (double)rand()`` – ThreeFx Jul 25 '14 at 21:33
  • 2
    You can actually do just `1/7.0` or `1.0/7`. As long as one value is floating point then you are OK. – rmaddy Jul 25 '14 at 21:41
  • How would I limit that then? I've been using random()&1500 to get a number between 0 and 1500, but that binary expression doesn't accept double values as operands. – Sparky Jul 25 '14 at 21:59
  • 1
    @Sparky ``random() & 1500`` does not return a "fair" random number between 0 and 1500. Doing `` + random() % ( - )`` generates a random number between the lower and upper bound as discussed in [this](https://stackoverflow.com/questions/9678373/generate-random-numbers-between-two-numbers-in-objective-c) question. Note that the lower bound is inclusive and the upper bound is exclusive. Also note that using ``arc4random()`` is better because it is superior to ``rand()``. – ThreeFx Jul 25 '14 at 22:02
  • 1
    And it's better to use `arc4random_uniform(X)` instead of `arc4random() % X`. – rmaddy Jul 25 '14 at 22:11