我很難弄清楚何時使用int,double和long。使用int,double和long來計算權力
我正在計算整數的功率並返回結果,只要所提供的功率不是負數。
對於任務,我需要使用下面的代碼開始:
public static long powerN(int number, int power) {
這就是我想出了:
public class PowerCalculator
{
/**
* Calculate the non-negative power of an integer number. If a negative power is input, the method returns 1.
*
* @param number The number to take power.
* @param power The power factor to be taken to.
* @return The calculation result after taking power of the integer number.
*/
public static long powerN(int number, int power) {
if (power > 0)
{
double result = (Math.pow(number, power));
return result;
}
else
{
return 1;
}
}
}
我知道我搞亂了使用int,double或long,但我不知道如何解決它。
看一看[這](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/ datatypes.html)。 –
我懷疑作業的目的不是使用'Math.pow',而是通過乘以正確的次數來計算功率。我會認爲那是你老師的意圖。如果你想使用'Math.pow',你應該學習鑄造。例如,要將double轉換爲long,您會說'(long)result'。但我不認爲這是他們想要的。 –
嗯。你可能是對的。我想我會更好地澄清。 – SweetMello7