VeryLongInt operator/ (const VeryLongInt& a, const VeryLongInt& b) { //判断被除数和除数的符号 int sign1 = 1; if (a.sign * b.sign < 0) { sign1 = -1; } //取绝对值进行计算 string num1 = a.s; string num2 = b.s; if (a.sign == -1) { num1 = num1.erase(0, 1); } if (b.sign == -1) { num2 = num2.erase(0, 1); } VeryLongInt dividend = num1; VeryLongInt divisor = num2; //特殊情况:除数为0,抛出异常 if (num2 == "0") { throw invalid_argument("division by zero"); } //如果被除数小于除数,商为0,余数为被除数 if (num2 > num1) { return VeryLongInt(0); } // 计算商和余数 VeryLongInt quotient, remainder; //quotient.base = dividend.base; //remainder.base = dividend.base; //quotient.sign = sign1; //remainder.sign = sign1; remainder.s = dividend.s.substr(0, divisor.s.length() - 1); for (int i = divisor.s.length() - 1; i < dividend.s.length(); i++) { remainder.s += dividend.s[i]; remainder.stripZeros();//移除余数的前导0 VeryLongInt temp; while (temp <= remainder) { temp += divisor; quotient += VeryLongInt(1); } quotient -= VeryLongInt(1);//减掉多加的1 remainder = remainder - (temp - divisor); remainder.removeLeadingZeros(); quotient.removeLeadingZeros(); } // 更新商和余数的符号 quotient.sign = sign1; remainder.sign = a.sign; return quotient; }这段代码在进行除法计算时有一定错误,要如何改善呢
时间: 2024-01-11 22:02:27 浏览: 59
DEL_ARR.rar_AⅴARrcom
这段代码在进行除法计算时有一些问题:
1. 当被除数小于除数时,应该返回0而不是空字符串。
2. 在计算商和余数时,将余数从被除数中取出时,应该取出 divisor.s.length() 个数字而不是 divisor.s.length() - 1 个数字。
3. 在计算商和余数时,循环条件应该是 i <= dividend.s.length() 而不是 i < dividend.s.length()。
4. 在计算商和余数时,应该在每次将商加1时,判断商是否大于等于10的当前进制次幂,如果是,需要将商的进制位数增加1。
5. 在计算商和余数时,应该在最后将商和余数都移除前导0。
6. 在更新商和余数的符号时,应该将商的符号设置为 sign1 * a.sign,而不是只设置为 sign1。
下面是修改后的代码:
```
VeryLongInt operator/ (const VeryLongInt& a, const VeryLongInt& b) {
// 判断被除数和除数的符号
int sign1 = 1;
if (a.sign * b.sign < 0) {
sign1 = -1;
}
// 取绝对值进行计算
string num1 = a.s;
string num2 = b.s;
if (a.sign == -1) {
num1 = num1.erase(0, 1);
}
if (b.sign == -1) {
num2 = num2.erase(0, 1);
}
VeryLongInt dividend = num1;
VeryLongInt divisor = num2;
// 特殊情况:除数为0,抛出异常
if (num2 == "0") {
throw invalid_argument("division by zero");
}
// 如果被除数小于除数,商为0,余数为被除数
if (num2 > num1) {
return VeryLongInt(0);
}
// 计算商和余数
VeryLongInt quotient, remainder;
int base = a.base;
quotient.base = base;
remainder.base = base;
quotient.sign = sign1;
remainder.sign = a.sign;
remainder.s = dividend.s.substr(0, divisor.s.length());
for (int i = divisor.s.length(); i <= dividend.s.length(); i++) {
remainder.stripZeros(); // 移除余数的前导0
VeryLongInt temp;
while (temp <= remainder) {
temp += divisor;
quotient += VeryLongInt(1);
if (quotient.s.length() > 1 && quotient.s[quotient.s.length() - 2] >= base) {
quotient.s[quotient.s.length() - 2] -= base;
quotient.s[quotient.s.length() - 1] += 1;
}
}
quotient -= VeryLongInt(1); // 减掉多加的1
remainder = remainder - (temp - divisor);
if (i < dividend.s.length()) {
remainder.s += dividend.s[i];
}
}
// 更新商和余数的符号
quotient.sign = sign1 * a.sign;
remainder.sign = a.sign;
quotient.removeLeadingZeros();
remainder.removeLeadingZeros();
return quotient;
}
```
阅读全文