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?
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
.