PDA

View Full Version : C Array Setting Fractions




Duke Leto
Jun 28, 2009, 04:45 PM
I have a class containing a few arrays a,b, and c. These are double values.

@interface ArrayContainer : NSObject
{
double a[10][10];
double b[10][2];
double c[10];
}

However, when I set the values to fractions, it is still 0!

...
a[2][1] = 1/5;
...

But if I set them directly, it works!

...
a[2][1] = .2;
...

Why don't these arrays work!?



lee1210
Jun 28, 2009, 04:53 PM
the token 1 is interpreted as an int with the value 1. 5 is the same. .2 is a double with the approximate value of .2. .2f would be a float with the approximate value of .2. When you do integer division, things truncate. 5 goes into 1 0 times, so the result is correct. After the integer division, there is a cast up to double, but the result is still 0.

-Lee

parapup
Jun 28, 2009, 04:55 PM
However, when I set the values to fractions, it is still 0!

...
a[2][1] = 1/5;
...

But if I set them directly, it works!

...
a[2][1] = .2;
...

Why don't these arrays work!

1/5 - both 1 and 5 are treated as integers by the compiler. So you need a explicit type cast like the below or use 1.0/5.0.


a[2][1] = (double)1/(double)5