C Array Setting Fractions

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

  1. macrumors regular

    Joined:
    Mar 17, 2008
    #1
    I have a class containing a few arrays a,b, and c. These are double values.
    Code:
    @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!
    Code:
    ...
    a[2][1] = 1/5;
    ...
    
    But if I set them directly, it works!
    Code:
    ...
    a[2][1] = .2;
    ...
    
    Why don't these arrays work!?
     
  2. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    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
     
  3. macrumors 65816

    parapup

    Joined:
    Oct 31, 2006
    #3
    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.

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

Share This Page