c++ 提供多種求次方的方法:使用 pow() 函數(shù)或 std::pow() 函數(shù),接受底數(shù)和指數(shù)參數(shù)。使用循環(huán),對于正整數(shù)指數(shù),按指數(shù)次乘以底數(shù)。使用二分查找算法,通過分治法快速求次方。對于負(fù)整數(shù)指數(shù),使用公式 1 / power(base, -exponent) 進(jìn)行計算。
C++ 中的求次方函數(shù)
C++ 中有多種方法可以求次方。最直接的方法是使用 pow()
函數(shù),它接受兩個參數(shù):底數(shù)和指數(shù)。例如:
<code class="cpp">#include <cmath> int main() { double base = 2.0; int exponent = 3; double result = pow(base, exponent); // 結(jié)果為 8.0 }</cmath></code>
登錄后復(fù)制
對于整數(shù)指數(shù),可以使用 std::pow()
函數(shù),它接受三個參數(shù):底數(shù)、整數(shù)指數(shù)和目標(biāo)類型。例如:
<code class="cpp">#include <cmath> int main() { int base = 2; int exponent = 3; int result = std::pow(base, exponent, long long); // 結(jié)果為 8 }</cmath></code>
登錄后復(fù)制
另一種方法是使用循環(huán)。例如,對于正整數(shù)指數(shù):
<code class="cpp">int power(int base, int exponent) { int result = 1; for (int i = 0; i </code>
登錄后復(fù)制
對于負(fù)整數(shù)指數(shù),可以使用以下公式:
<code class="cpp">int power(int base, int exponent) { if (exponent == 0) { return 1; } else if (exponent </code>
登錄后復(fù)制
最后,還可以使用二分查找算法來快速求次方。例如:
<code class="cpp">int power(int base, int exponent) { if (exponent == 0) { return 1; } else if (exponent 0) { if (exponent % 2 == 1) { result *= base; } base *= base; exponent /= 2; } return result; } }</code>
登錄后復(fù)制