Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

java - Calculations for the volume of a sphere is incorrect

I can't seem to figure out why the calculation for the volume is giving me incorrect numbers. With a radius of 4.2 the volume should be about 310. I'm also 99% sure my formula is correct as-well.

package ch3_program2;

import java.util.Scanner;

public class SphereCalculations {

    public static void main(String[] args) {

        double r;
        System.out.println("Welcome to the Sphere Calculator.");
        
        Scanner scan = new Scanner(System.in);
        
        System.out.print("Enter the sphere's radius: ");
        r = scan.nextDouble();
        System.out.println();
        
        System.out.println("The Results are:");
        System.out.println("Radius: " + r);
        System.out.println("Volume: " + 4/3 * Math.PI * Math.pow(r, 3));
        System.out.println("Surface area: " + 4 * Math.PI * Math.pow(r, 2));
        
        scan.close();
    }

}

The output I am getting:
Welcome to the Sphere Calculator.
Enter the sphere's radius: 4.2

The Results are:
Radius: 4.2
Volume: 232.75431651916062
Surface area: 221.6707776372958

question from:https://stackoverflow.com/questions/66057886/calculations-for-the-volume-of-a-sphere-is-incorrect

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your problem is integer arithmetic: 4/3 is 1.

Change 4/3 to 4D/3, or swap to Math.PI * 4/3 to force double arithmetic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...