在本教程中,我们将看到如何在 Java 中计算圆的面积和周长。有两种方法可以做到这一点:
1)用户交互:程序将提示用户输入圆的半径
2)没有用户交互:半径值将在程序本身中指定。
计划 1:
/** * @author: BeginnersBook.com * @description: Program to calculate area and circumference of circle * with user interaction. User will be prompt to enter the radius and * the result will be calculated based on the provided radius value. */import java.util.Scanner;class CircleDemo{ static Scanner sc = new Scanner(System.in); public static void main(String args[]) { System.out.print("Enter the radius: "); /*We are storing the entered radius in double * because a user can enter radius in decimals */ double radius = sc.nextDouble(); //Area = PI*radius*radius double area = Math.PI * (radius * radius); System.out.println("The area of circle is: " + area); //Circumference = 2*PI*radius double circumference= Math.PI * 2*radius; System.out.println( "The circumference of the circle is:"+circumference) ; }}
输出:
Enter the radius: 1The area of circle is: 3.141592653589793The circumference of the circle is:6.283185307179586
程序 2:
/** * @author: BeginnersBook.com * @description: Program to calculate area and circumference of circle * without user interaction. You need to specify the radius value in * program itself. */class CircleDemo2{ public static void main(String args[]) { int radius = 3; double area = Math.PI * (radius * radius); System.out.println("The area of circle is: " + area); double circumference= Math.PI * 2*radius; System.out.println( "The circumference of the circle is:"+circumference) ; }}输出:
The area of circle is: 28.274333882308138The circumference of the circle is:18.84955592153876
