小数幂次c++高精度代码
时间: 2024-08-17 15:01:59 浏览: 67
小数幂次计算在C++中通常涉及到高精度数学,因为直接对浮点数进行乘方可能会导致精度丢失。如果你需要处理非整数幂,可以使用一种称为“牛顿法”或者“二分法”的算法结合字符串或大数库来进行。这里提供一个简单的基于stringstream的大数乘法和除法的示例:
```cpp
#include <sstream>
#include <iostream>
std::string multiply(const std::string &a, const std::string &b) {
int n1 = a.size(), n2 = b.size();
if (n1 == 0 || n2 == 0)
return "0";
std::vector<int> res(n1 + n2);
for (int i = n1 - 1; i >= 0; --i) {
long long int carry = 0;
for (int j = n2 - 1; j >= 0; --j) {
int sum = (a[i] - '0') * (b[j] - '0') + carry + res[i + j];
res[i + j] = static_cast<int>(sum % 10);
carry = sum / 10;
}
if (carry > 0)
res[i] += carry;
}
std::reverse(res.begin(), res.end());
return std::string(res.begin(), res.end());
}
std::string divide(const std::string ÷nd, const std::string &divisor) {
int n1 = dividend.size(), n2 = divisor.size();
if (n2 == 0)
return "1";
bool negative = (dividend[0] - '0') < 0 ^ (divisor[0] - '0' < 0);
dividend = std::abs(dividend);
divisor = std::abs(divisor);
std::string result = "0.";
while (!dividend.empty()) {
int shift = 1;
for (int i = 1; i < divisor.size(); ++i) {
shift *= 10;
dividend.pop_back();
}
int quotient = 0;
for (int i = 0; i < divisor.size(); ++i) {
quotient += ((dividend.back() - '0') * shift) / (divisor[i] - '0');
dividend.pop_back();
}
result.push_back(quotient + '0');
}
return negative ? "-" + result : result;
}
std::string power(std::string base, double exponent) {
std::string result("1");
while (exponent != 0) {
if (exponent > 0) {
result = multiply(result, base);
exponent--;
} else {
exponent++;
base = divide(base, "10"); // 这里假设我们只支持小数部分不超过一位的情况
}
}
return result;
}
int main() {
std::cout << power("12345", 2.5) << std::endl; // 示例:输出以特定精度表示的12345^2.5
return 0;
}
```
阅读全文