Results 1 to 3 of 3
  1. #1
    jeanOliver is offline Member
    Join Date
    Sep 2011
    Posts
    1
    Rep Power
    0

    Default trouble using fractions

    Hi everyone
    I'm new to this forum and to java, and have a rather simple question:

    I want to use the fraction 1/12, but as an answere, i always get 0.0.

    for example:

    double a= 1/12;

    System.out.println("a= "+a);

    which will give me the result : a= 0.0;




    what can I do to use fractions correctly?

    Thanks in advance.

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,013
    Rep Power
    10

    Default Re: trouble using fractions

    Raw integers (numbers without a decimal point) are considered ints- they are only whole numbers (0, 1, 76, -45), so you lose anything after the decimal point.

    Try to do it the other way: what happens when you divide a big number by a small number? Try 12/5, for example.

    One solution would be to use them as raw doubles (numbers with a decimal point). Try 1.0/12.0. You could also cast one (or both) of them:

    double a = ((double)1)/12

    When you mix a double and an int, the answer is considered a double.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,453
    Rep Power
    20

    Default Re: trouble using fractions

    Quote Originally Posted by KevinWorkman View Post
    When you mix a double and an int, the answer is considered a double.
    Initially, it's just a little fraction, but yes, it grows up to be a double.

    db

Similar Threads

  1. GUI Trouble
    By rvgsd in forum New To Java
    Replies: 2
    Last Post: 03-07-2010, 01:10 AM
  2. Reducing fractions
    By SwEeTAcTioN in forum New To Java
    Replies: 10
    Last Post: 01-13-2010, 05:51 PM
  3. NumberFormat which leave fractions as they are
    By itaipee in forum AWT / Swing
    Replies: 2
    Last Post: 12-09-2009, 07:11 PM
  4. How do I reduce Fractions in this program?
    By Popedreadlock in forum New To Java
    Replies: 8
    Last Post: 12-08-2008, 01:28 AM
  5. having some trouble
    By Unknown1369 in forum New To Java
    Replies: 13
    Last Post: 07-22-2008, 12:52 AM

Posting Permissions

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