Results 1 to 4 of 4

Thread: Exercises

  1. #1
    lclclc is offline Member
    Join Date
    Aug 2009
    Posts
    22
    Rep Power
    0

    Default Exercises

    I have a question about priniting out volume and surface area of a sphere.
    I have written out the code, However, I am unable to obtain the correct output for the volume. May I know where is my mistake?

    Belows are my work out code.
    <code> int radius;
    double volume,surfaceArea;
    //final double PI = 3.142;

    Scanner scan = new Scanner(System.in);

    System.out.print("Give the radius of circle: ");
    radius = scan.nextInt();

    volume = (double)((4/3)*Math.PI*Math.pow(radius,3));
    surfaceArea = (double)(4*Math.PI*Math.pow(radius,2));

    DecimalFormat fmt = new DecimalFormat("0.####");

    System.out.println("The circle's volume is "+fmt.format(volume)+" and it's surface area is "+fmt.format(surfaceArea)+'.');
    </code>
    Thank you for any help and reply.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Change (4/3) to ((double)4/3) if you want to avoid int division here. Perhaps even better would be to just use double numeric constants:
    (4.0/3.0)

  3. #3
    lclclc is offline Member
    Join Date
    Aug 2009
    Posts
    22
    Rep Power
    0

    Default

    Thank you Fubarable.
    But, May I know why is this so?


    thank you for your help.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    thank you for your help.
    (4/3) will result in int division which returns an int (it will return 1 in fact). You don't want int division, but rather want floating point division so that you can have a floating point result returned.

Posting Permissions

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