Conor Taylor
Conor Taylor

Reputation: 3108

Float only printing whole numbers?

Why is it that when I run this code in a loop, only whole numbers are printed in the console?

for (int i = 1; i <= 50; i++) {
        zombieSpeed[i] = (((arc4random()%40)+2)/7);
        NSLog(@"%f", zombieSpeed[i]);
}

Upvotes: 1

Views: 127

Answers (3)

phoxis
phoxis

Reputation: 61970

The division is an integer division, use explicit decimal point as 40.0 or typecast, so that at least one operand is floating point, which upcasts the entire expression to be evaluated as floating point. Make sure that any left hand side variable to which you assign the computer value is of floating point type with equal or greater width (to preserve the precision).

Upvotes: 1

Andy
Andy

Reputation: 50630

This line needs to use Float values (40.0, 2.0, 7.0)

zombieSpeed[i] = (((arc4random()%40)+2)/7);

Upvotes: 2

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

The problem is here

zombieSpeed[i] = (((arc4random()%40)+2)/7);

instead of 40, 2, 7 you should use 40.0, 2.0, 7.0

Also make sure that ZombieSpeed is of float type

Upvotes: 4

Related Questions