order of operations with division and multiplication

Discussion in 'C++' started by Tim923, Apr 8, 2005.

  1. Tim923

    Tim923 Guest

    The following lines were tried:

    x1 = (-b + sqrt(pow(b,2)-(4*a*c))) /(2*a);

    x1 = (-b + sqrt(pow(b,2)-(4*a*c))) / 2*a;


    I noticed that the last parentheses were optional and didn't change
    anything.
    Although if I mean 1/(2*5)=0.1 then 1/2*5=2.5 is not the same. What
    is the difference?
    Tim923, Apr 8, 2005
    #1
    1. Advertising

  2. Tim923

    Pete Becker Guest

    Tim923 wrote:
    > The following lines were tried:
    >
    > x1 = (-b + sqrt(pow(b,2)-(4*a*c))) /(2*a);
    >
    > x1 = (-b + sqrt(pow(b,2)-(4*a*c))) / 2*a;
    >
    >
    > I noticed that the last parentheses were optional and didn't change
    > anything.
    > Although if I mean 1/(2*5)=0.1 then 1/2*5=2.5 is not the same. What
    > is the difference?
    >


    It's not order, but grouping. That is, you have to be sure that each
    operation gets applied to the correct operands. Generally speaking, math
    operators group from left to right, so a/b*c says that a should be
    divided by b, and the result multiplied by c. To change this grouping,
    add parentheses: a/(b*c).

    --

    Pete Becker
    Dinkumware, Ltd. (http://www.dinkumware.com)
    Pete Becker, Apr 8, 2005
    #2
    1. Advertising

  3. Tim923

    Evan Guest

    It should matter, and does for me. Sure you tried it with something
    other than a=1?
    Evan, Apr 8, 2005
    #3
  4. Tim923

    marbac Guest

    Tim923 wrote:

    > Although if I mean 1/(2*5)=0.1 then 1/2*5=2.5 is not the same. What
    > is the difference?
    >


    The Rank of both operators / and * is the same in the second example,
    but the associativity in this case is from left to right. That means
    that operator 1/2 is calculated first, after this 1/2 is multiplied by 5.

    Due to higher Rank of "()" 2*5 is calculated before the division in the
    first example.
    marbac, Apr 8, 2005
    #4
  5. Tim923

    Tim923 Guest

    Evan wrote:
    >It should matter, and does for me. Sure you tried it with something
    >other than a=1?


    That's it. I think a was 1.
    Tim923, Apr 8, 2005
    #5
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    1
    Views:
    787
    Thomas Matthews
    Jan 21, 2005
  2. William Hughes
    Replies:
    13
    Views:
    1,204
    Ben Bacarisse
    Mar 15, 2010
  3. Eric Sosman
    Replies:
    1
    Views:
    482
    Eric Sosman
    May 13, 2010
  4. Keith Thompson
    Replies:
    2
    Views:
    724
    Seebs
    May 13, 2010
  5. Francois Grieu
    Replies:
    0
    Views:
    285
    Francois Grieu
    Jun 8, 2010
Loading...

Share This Page