C Array Setting Fractions

Discussion in 'Mac Programming' started by Duke Leto, Jun 28, 2009.

  1. Duke Leto
    Expand Collapse
    macrumors regular

    Mar 17, 2008
    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!?
  2. lee1210
    Expand Collapse
    macrumors 68040


    Jan 10, 2005
    Dallas, TX
    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.

  3. parapup
    Expand Collapse
    macrumors 65816


    Oct 31, 2006
    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 

Share This Page