21xrx.com
2025-03-23 20:22:42 Sunday
文章检索 我的文章 写文章
如何在Java中计算一个数的平方?
2023-06-16 09:43:42 深夜i     13     0
Java 平方 Math类

在Java中,我们可以使用Math类的pow方法来计算一个数的平方。该函数接收两个参数,第一个参数是要计算平方的数,第二个参数是指数,也就是要计算的幂次。

下面是一个简单的示例代码,演示如何使用pow方法来计算一个数的平方:

import java.lang.Math;
public class Main {
 public static void main(String[] args) {
  double num = 5;
  double square = Math.pow(num, 2);
  System.out.println("The square of " + num + " is " + square);
 }
}

在上面的代码中,我们首先定义了一个double类型的变量num,并将其赋值为5。然后,我们使用Math.pow方法来计算num的平方,并将结果保存在square变量中。最后,我们使用System.out.println方法将计算结果输出到控制台。

  
  

评论区