在字符串java中,四舍五入到小数后添加字符串时出现问题

在字符串java中,四舍五入到小数后添加字符串时出现问题,java,Java,如果你们能帮我的话,我的代码有两个问题。第一个问题是volume=4/3*Math.PI*Math.pow(半径,3)计算不正确,当我为半径输入1.0时,应为4.18879。我很困惑,因为其他人计算正确。对于第二个问题,我的家庭作业要求我在打印答案后加上句号。我尝试了System.out.printf(“卷是%.5f\n”,卷+”)但它打印了。在下一行,而不是在同一行。我试过很多其他的方法,但我想不出来。很抱歉格式太糟糕了,这是我的第一篇文章 import java.util.Scanner;

如果你们能帮我的话,我的代码有两个问题。第一个问题是
volume=4/3*Math.PI*Math.pow(半径,3)计算不正确,当我为半径输入1.0时,应为4.18879。我很困惑,因为其他人计算正确。对于第二个问题,我的家庭作业要求我在打印答案后加上句号。我尝试了
System.out.printf(“卷是%.5f\n”,卷+”)但它打印了。在下一行,而不是在同一行。我试过很多其他的方法,但我想不出来。很抱歉格式太糟糕了,这是我的第一篇文章

import java.util.Scanner;
public class P2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // Declare variables for geometric formulas
        double radius;
        double circumference;
        double area;
        double volume;

        // Instantiate scanner
        Scanner keyboard = new Scanner(System.in);

        // Prompt and read radius from keyboard
        System.out.print("Radius? ");
        radius = keyboard.nextDouble();

        // Calculate circumference, area, and volume
        circumference = 2 * Math.PI * radius;
        area = Math.PI * Math.pow(radius, 2);
        volume = 4/3 * Math.PI * Math.pow(radius, 3);

        // Print circumference, area, and volume to console
        System.out.printf("The circumference is %.5f\n", circumference);
        System.out.printf("The area is %.5f\n", area);
        System.out.printf("The volume is %.5f\n", volume);

        // Declare variables for converting mass to energy
        double energy;
        double mass;
        double speedOfLight = 299792458.0;


        // Prompt and read mass from keyboard
        System.out.print("Mass? ");
        mass = keyboard.nextDouble();

        // Compute the energy using the formula
        energy = mass * (Math.pow(speedOfLight, 2));

        // Print energy to console
        System.out.printf("The energy is %.1f\n joules.", energy);

        // Close scanner
        keyboard.close();
    }

}

     1. sample code: 
     - Radius? 1.0 
     - The circumference is 6.28319.
     - The area is 3.14159.
     - The volume is 4.18879. 
     - Mass? 1.0 
     - The energy is 89875517873681760.0 joules.

当你做4/3,这是整数除法,所以当你真的想要1.33333时,结果总是1。。。你应该这样做

volume = 4.0/3.0 * Math.PI * Math.pow(radius, 3);
4.0/3.0将确保您通过除以双精度而不是整数得到正确的结果

System.out.printf("The volume is %.5f.\n", volume);

由于整数除法,4/3将计算为1。要得到1.333。。。你必须这样做

4f / 3
这将把4转换成一个浮点数,所以你得到一个浮点数,它实际上可以容纳1.333

至于你的产出:

System.out.println("The volume is " + volume + ".");