不能从 float 转换为 double?

cannot convert from float to double?

The formula to calculate the area of a circumference is defined as x = π . R2. Considering to this problem that π = 3.14159:

Calculate the area using the formula given in the problem description.

Input The input contains a value of floating point (double precision), that is the variable R.

对于输入 2,我应该将 x=12.5664 四舍五入一个数字。

我尝试使用这个简单的代码,但我不记得如何处理“无法从双精度转换为浮点”错误。码字半年了

package TEST;
import java.util.Scanner;
public class TEST {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    // let A be radius
    float A = scanner.nextFloat();
    float A_2 = A * A;
    // let B be Pi
    double B = 3.14159;
    
    // let x be circumference
    float x = A_2 * B;
    
    System.out.printf("x= %.4f" + x);

    
    }}

你可以试试:

double A_2Converted = (double) A_2;

并使用它。

来源:Convert float to double without losing precision

编译错误的原因是以下赋值:

float x = A_2 * B;

其中 Bdouble 类型,因此乘积的结果将是 double 类型,不能容纳到 [=16] 类型的变量中=].请记住:double 需要 8 个字节的 space 而 float 变量只能容纳 4 个字节。

更正此编译错误后,您将遇到运行时间错误,因为您使用了加号(+)而不是逗号(,) 在 printf 语句中。

除此之外,

  1. 始终遵循 Java 命名约定,例如按照惯例,A 应该是 aA_2 应该是 a2
  2. 您可以使用 Math.PI 而不是为 PI 使用您自己的值。

以下代码合并了这些更改:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // let a be radius
        float a = scanner.nextFloat();
        float a2 = a * a;
        // let b be PI
        double b = Math.PI;

        // let x be circumference
        double x = a2 * b;

        System.out.printf("x= %.4f", x);
    }
}

样本运行:

2
x= 12.5664