Java Question
Results 1 to 5 of 5

Thread: Java Question

  1. #1
    Senior Member
    Join Date
    Jan 2004
    Posts
    199

    Java Question

    One of the rules when working with java is :
    ( *, /, % ) takes precendence over ( + , - )


    So how comes the result produces 2.5, and not 3 (to get 3 i did three/two first = 1.5 and then added 1.5 to it - this follows the above rule

    ------------------------
    int three = 3;
    int two = 2;
    double result;

    result = 1.5 + three/two;


    result = 2.5
    -------------------------

    Am i over looking, or doing something really stupid ? Any ideas ?
    -

  2. #2
    Senior Member
    Join Date
    Jun 2003
    Posts
    772
    Try using a double for the vars two and three instead of an int. Should work I think.
    Seems three/two is seen as an integer and rounded down?
    The above sentences are produced by the propaganda and indoctrination of people manipulating my mind since 1987, hence, I cannot be held responsible for this post\'s content - me

    www.elhalf.com

  3. #3
    Senior Member
    Join Date
    Aug 2003
    Posts
    1,019
    Or another way of looking at it is 2 only goes into 3 one time..el-half is correct, if you want the correct value to come out of the division portion, at least one needs to be a double value.

    EDIT: ie 1/3=0, but 1.0/3.0=.3333333e

    Another way of doing it would be <var>=2.5 + (double) 3/2;

  4. #4
    AO Antique pwaring's Avatar
    Join Date
    Aug 2001
    Posts
    1,409
    Doing (double) 3/2 will not return the correct result, because Java will calculate the result as an integer division and round down to 1, then cast to a double giving 1.0.

    Either specify one of two/three as a double or do the following:

    result = 1.5 + (((double) three) / two)

    Casting has low precedence in relation to arithmetic operations so it will cast the result if you don't use brackets rather than casting the number.
    Paul Waring - Web site design and development.

  5. #5
    Senior Member
    Join Date
    Aug 2003
    Posts
    1,019
    Yep, I forgot to add the brackets, and I posted incorrect info, and I knew better

    /me slaps self on head

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •