1

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.

And for an input of 2, I should be getting x=12.5664 rounded by one number.

I tried using this simple code, but I couldn't remember what to do with the "cannot convert from double to float" error. It's been half a year since I coded.

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);

    
    }}

2 Answers2

3

The cause of the compilation error is the following assignment:

float x = A_2 * B;

where B is of type, double and therefore the result of the product will of type, double which can not be accommodated into a variable of type, float. Remember: double requires 8 bytes of space whereas a float variable can accommodate only 4 bytes.

After correcting this compilation error, you will encounter a runtime error because you have used a plus sign (+) instead of a comma (,) inside the printf statement.

Apart from this,

  1. Always follow Java naming conventions e.g. A should be a and A_2 should be a2 following the conventions.
  2. You can use Math.PI instead of using your own value for PI.

The following code incorporates these changes:

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);
    }
}

A sample run:

2
x= 12.5664
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

You could try:

double A_2Converted = (double) A_2;

and use that.

source: Convert float to double without losing precision

FrankDad
  • 23
  • 7