闲来无事写了一个高精度四则运算,结果除法部分遇到了一些问题。 以下是除法部分的代码。
int compare(const std::string& lhs, const std::string& rhs) {
if (lhs.length() < rhs.length()) return -1;
if (lhs.length() > rhs.length()) return 1;
for (size_t i = 0; i < lhs.length(); i++) {
if (lhs[i] < rhs[i]) return -1;
if (lhs[i] > rhs[i]) return 1;
}
}
std::string divide(std::string dividend, std::string divisor) {
if (divisor == "0") return "Error: Divisor is zero";
if (compare(dividend, divisor) < 0) return "Error: Divisor is greater than dividend";
std::string quotient = "";
std::string remainder = "0";
for (size_t i = 0; i < dividend.length(); ++i) {
if (remainder == "0") {
remainder = dividend[i];
} else {
remainder = remainder + dividend[i];
}
int count = 0;
while (compare(remainder, divisor) >= 0) {
remainder = subtract(remainder, divisor);
++count;
}
quotient += char(count + '0');
}
while (quotient.length() > 1 && quotient[0] == '0') quotient.erase(0, 1);
return quotient;
}
其中的subtract函数代码片段在这:
std::string subtract(std::string a, std::string b) {
std::string result;
while (b.size() < a.size()) b = "0" + b;
for (int i = a.size() - 1; i >= 0; --i) {
if (a[i] < b[i]) {
a[i] += 10;
a[i - 1]--;
}
result = char(a[i] - b[i] + '0') + result;
}
while (result.size() > 1 && result[0] == '0') result.erase(0, 1);
return result;
}
目前的问题是这样的,如果输入过大数字(具体多大我懒得去试了),程序输出1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 反之则正常。
请问有大佬知道怎么解决吗?
Tips:减法函数确定没有异常,减法默认a比b大。 违规紫杉