Help in C Arithmetics

Discussion in 'Mac Programming' started by uaecasher, Jun 15, 2009.

  1. macrumors 65816

    uaecasher

    Joined:
    Jan 29, 2009
    Location:
    Stillwater, OK
    #1
    Hello,

    i have written this code:

    Code:
    
    #include <stdio.h> 
    int main (void) 
    { 
    	
    	int a = 15;
    	int b = 35;
    	
    	
    printf("a / b * b = %i\n", a / b * b);
    
    	
    } 
    
    
    
    the result i get is zero, but it should be 15, why I'm getting a 0

    thanks
     
  2. Wes
    macrumors 68020

    Wes

    Joined:
    Jun 22, 2001
    Location:
    London
    #2
    You need to think about the order this is being evaluated, see: http://www.difranco.net/cop2220/op-prec.htm

    a / b * b becomes (a / b) * b

    where:
    a = 15;
    b = 35;

    (15/35)*35
    0*35

    Remember these are integers so 15/35 will be 0. If you want to get the fractional part you'll need to use floats or doubles.
     
  3. EMT
    macrumors newbie

    Joined:
    May 25, 2009
    #3
    Use parenthesis in your expressions to make it safe.:
     
  4. macrumors 6502

    Joined:
    Apr 24, 2008
    #4
    That wouldn't help in this case - it's the integer division that's the problem here.
     
  5. macrumors G5

    gnasher729

    Joined:
    Nov 25, 2005
    #5
    It should be zero. Buy a C book for beginners.
     

Share This Page