CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Sep 1999
    Location
    Ottawa, Ontario, Canada
    Posts
    7

    I have a java math problem

    When we calculate 4/6 on an ordinary calculator, the answer is 0.6666666666667 right? But when we ask java to calculate 4/6 (assuming that 4 and 6 are 'floats' as in real numbers), java would display an answer of 0.0, but we know that 0.0 does not equal to 4/6. So my question is how do we 'teach' java to tell it that 4/6 is 0.66666666667 not 0.0.

    This is the section of my program that I am having problems

    int gear1;
    int gear2;
    int gear3;

    System.out.print("Please enter the number of sprokets of the gear 1...");
    gear1 =
    Integer.valueOf(inputStream.readLine().trim()).intValue();

    System.out.print("Please enter the number of sprokets of the gear 2...");
    gear2=
    Integer.valueOf(inputStream.readLine().trim()).intValue();

    System.out.print("Please enter the number of sprokets of the gear 3...");
    gear3=
    Integer.valueOf(inputStream.readLine().trim()).intValue();

    System.out.println("The number of sprokets on gear 1 is " + gear1);
    System.out.println("The number of sprokets on gear 2 is " + gear2);
    System.out.println("The number of sprokets on gear 3 is " + gear3);

    float Ratio1;
    float Ratio2;

    ratio1 = (gear1 / gear2);
    ratio2 = (gear2 / gear3);

    System.out.println("The gear ratio between gear 2 and gear 1 is " + ratio1);
    System.out.println("The gear ratio between gear 3 and gear 2 is " + ratio2);


  2. #2
    Join Date
    May 1999
    Location
    Pune, MH, India.
    Posts
    453

    Re: I have a java math problem

    I think u r doing integer division that's why u r getting '0.0'

    Try this...


    ratio1 = ((float)gear1 / gear2);
    ratio2 = ((float)gear2 / gear3);




    in ur code, and it should give u proper result in fractions.

    - UnicMan
    http://members.tripod.com/unicman

  3. #3
    Join Date
    Sep 1999
    Posts
    3

    Re: I have a java math problem

    Hello Beavis,

    the problem is that gear1, gear2 and gear3 should be of type float or double, but in your example they are of type int, so java will perform an integer division and not a float/number division.

    Giorgio


Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured