StockAZ89
StockAZ89

Reputation: 51

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

Upvotes: 0

Views: 391

Answers (1)

Bohemian
Bohemian

Reputation: 425198

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.

Upvotes: 2

Related Questions