生活随笔
收集整理的這篇文章主要介紹了
题目11 数值的整数次方
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/
// 1. 題目11 數值的整數次方
// 1.1 沒有考慮負數和0的情況!!!!
double Power(
double dBase,
int iExponent)
{double dRes =
1.0;for (
int i =
0; i < iExponent; i++
){dRes *=
dBase;}return dRes;
}// 判斷兩個double是否相等
bool Equal(
double lhs,
double rhs)
{if ((lhs - rhs > -
0.0000001) && (lhs - rhs <
0.0000001)){return true;}return false;
}double PowerWithUnsignedExponent(
double dBase, unsigned
int uiExponent)
{double dResult =
1.0;for (unsigned
int i =
1; i <= uiExponent; i++
){dResult *=
dBase;}return dResult;
}// 1.2 全面但不夠高效的算法
double Power_1(
double dBase,
int iExponent)
{double dResult =
0.0;if (Equal(dBase,
0.0) && iExponent <
0){return dResult;}unsigned int absExponent = (unsigned
int)iExponent;if (iExponent <
0){absExponent = (unsigned
int)(-
iExponent);}dResult =
PowerWithUnsignedExponent(dBase, absExponent);if (iExponent <
0){dResult =
1.0 /
dResult;}return dResult;
}// 1.3 全面且高效的解法
// eg 如果輸入iExponent = 32, PowerWithUnsignedExponent中需要循環31次
// 另一種解法: (a)32 --> ((a)16)2 --> (((a)8)2)2 -> ... --> (((((a)2)2)2)2)2 --> 運行5次double NewPowerWithUnsignedExponent(
double dBase, unsigned
int uiExponent)
{if (
0 ==
uiExponent){return 1.0;}else if (
1 ==
uiExponent){return dBase;}double dResult = NewPowerWithUnsignedExponent(dBase, uiExponent >>
1);dResult *=
dResult;// 如果是基數if (uiExponent &
0x01){dResult *=
dBase;}return dResult;
}double Power_2(
double dBase,
int iExponent)
{double dResult =
0.0;if (Equal(dBase,
0.0) && iExponent <
0){return dResult;}unsigned int absExponent = (unsigned
int)iExponent;if (iExponent <
0){absExponent = (unsigned
int)(-
iExponent);}dResult =
NewPowerWithUnsignedExponent(dBase, absExponent);if (iExponent <
0){dResult =
1.0 /
dResult;}return dResult;
}void PowerTestFunc()
{cout <<
"\n\n --------------- PowerTestFunc Start -------------->" <<
endl;int aiArray[] = {-
3, -
2, -
1,
0,
1,
2,
3,
4,
5,
6};int iLen =
sizeof(aiArray) /
sizeof(
int);double dBase =
5;cout <<
"方法一: ==========================>>" <<
endl;for (
int i =
0; i < iLen; i++
){printf("[%lf] 的 %d 次方: %lf\n", dBase, aiArray[i], Power(dBase, aiArray[i]));}cout <<
"方法二: ==========================>>" <<
endl;for (
int i =
0; i < iLen; i++
){printf("[%lf] 的 %d 次方: %lf\n", dBase, aiArray[i], Power_1(dBase, aiArray[i]));}cout <<
"方法三: ==========================>>" <<
endl;for (
int i =
0; i < iLen; i++
){printf("[%lf] 的 %d 次方: %lf\n", dBase, aiArray[i], Power_2(dBase, aiArray[i]));}cout <<
"\n\n --------------- PowerTestFunc End -------------->" <<
endl;}
轉載于:https://www.cnblogs.com/yzdai/p/11258684.html
總結
以上是生活随笔為你收集整理的题目11 数值的整数次方的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。