c program arithmetic, getting wrong output .

Discussion in 'C' started by rveri, Jun 2, 2013.

  1. rveri

    rveri New Member

    Joined:
    May 17, 2013
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    Hi Experts,
    - I am trying to get output of exponent of a and b 's sum.
    Can you please advise why getting wrong output here:


    Code:
    $ cat t1.c
    #include <stdlib.h>
    #include <stdio.h>
    main (){
    int a,b,c,d=2;int r; /* Integers  */
    [COLOR="Green"]r=(a^2+b^2)[/COLOR];
    printf ("Hello:int practice ..: int a,b,c,d :: r=%d\n",r);
    
    exit(0);
    }
    
    Code:
    ./t1
    Hello:int practice ..: int a,b,c,d :: [COLOR="Red"]r=32771[/COLOR]
    - Value of r should be 8 , instead of 32771 , right ..

    Thanks,
     
  2. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    Not quite; you're using unitialize values for both a and b, but there's more. ^ the xor operator and not square; the code you've posted gets interesting... without inner parens, you may get a side effect from the addition along side the value of xor operation

    Code:
    int a = 2, b = 2, r
    r=(a^2+b^2);
    
    // 2^2 + 2^2
    
    //      010 
    // xor 
    //      010
    // -------
    /       000
     
    0 + 2 + 2 + 0 = 4 
    
    If you want the square, create your own function or maybe include math.h and use pow.
     
  3. rveri

    rveri New Member

    Joined:
    May 17, 2013
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    Thanks much..got it..
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice