CodeGym/Java Blog/Toto sisi/如何在 Java 中對數字求平方
John Squirrels

San Francisco

如何在 Java 中對數字求平方

如何在 Java 中對數字求平方？

示例 1

``````package com.square.java;
public class AlgebricSquare {

public static int getSquare(int number) {
return number * number;
}

public static void main(String[] args) {

int number = 2;
System.out.println("Square of " + number + " is: " + getSquare(number));

number = 5;
System.out.println("Square of " + number + " is: " + getSquare(number));

number = 7;
System.out.println("Square of " + number + " is: " + getSquare(number));
}
}``````

輸出

2 的平方是：4 5 的平方是：25 7 的平方是：49

示例 2

``````package com.square.java;
public class MathSquare {

public static final Integer POW = 2;
public static Double getSquare(Double number) {
return Math.pow(number, POW);
}

public static void main(String[] args) {

Double number = 3.5;
System.out.println("Square of " + number + " is: " + getSquare(number));

number = 11.1;
System.out.println("Square of " + number + " is: " + getSquare(number));

number = 13.0;
System.out.println("Square of " + number + " is: " + getSquare(number));
}
}``````

輸出

3.5 的平方是：12.25 11.1 的平方是：123.21 13.0 的平方是：169.0