Java 程序:给定半径求圆面积

原文:https://www.studytonight.com/java-programs/java-program-to-find-the-area-of-a-circle-given-the-radius

在本教程中,我们将学习如何使用递归函数找到两个数字的乘积。递归函数是调用自身的函数。但是在继续之前,如果你不熟悉 java 中嵌套 if 语句的概念,那么一定要查看主题为【Java 中的 T0】条件语句的文章。

输入:输入圆的半径:7.5

输出:圆的面积为:176.78

程序 1:计算和显示圆的面积

在这个程序中,我们将看到在给定半径的情况下如何计算圆的面积。

算法:

  1. 开始

  2. 创建 Scanner 类的实例。

  3. 声明一个变量来存储半径。

  4. 要求用户初始化变量。

  5. 使用公式计算圆的面积。

  6. 打印结果。

  7. 停下来。

让我们看下面的程序来理解上面的算法。

//Java Program to find the area of a circle given the radius
import java.util.Scanner;
public class Main
{
    public static void main(String[] args) 
    {
        int r;
        double pi = 3.14, area;
        //Take input from the user
        //Create an instance of the Scanner Class
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the radius of circle: ");
        r = sc.nextInt();
        area = pi * r * r;
        System.out.println("The area of the circle: "+area);
    }            
}

输入圆的半径:9 圆的面积:254.34

程序 2:计算和显示圆的面积

在这个程序中,我们将看到如何使用继承来计算给定半径时圆的面积。

算法:

  1. 开始

  2. 创建 Scanner 类的实例。

  3. 声明一个变量来存储半径。

  4. 要求用户初始化变量。

  5. 创建 Main 类的对象。

  6. 使用继承来寻找圆的面积。

  7. 打印圆的面积。

  8. 停止

让我们看下面的程序来理解上面的算法。

//Java Program to find the area of a circle given the radius
import java.util.Scanner;
class AreaOfCircle
{
    double area;
    void circle(double rad)
    {
     area= (22*rad*rad)/7;
    }
}
public class Main extends AreaOfCircle
{
   public static void main(String args[]) 
    {   
      //Take input from the user
      //Create an instance of the Scanner Class    
      Scanner s= new Scanner(System.in);
      System.out.println("Enter the radius of the circle: ");
      double radius= s.nextDouble();      
      Main a=new Main();
      a.circle(radius);
      System.out.println("The area of the circle is: " + a.area);      
   }
 }

输入圆的半径:5 圆的面积是:78。58860 . 88888888861