C++ 字符串乘法算法:实现大整数乘法
#include
class math_tool { public: static void getvalue(const char *first, const char *second); };
void math_tool::getvalue(const char *first, const char *second) { int length1 = strlen(first); int length2 = strlen(second);
// 用于存储结果的数组,最大长度为 length1 + length2
int result[length1 + length2] = {0};
for (int i = 0; i < length1; i++)
{
for (int j = 0; j < length2; j++)
{
result[i + j] += (first[i] - '0') * (second[j] - '0');
}
}
for (int i = length1 + length2 - 1; i > 0; i--)
{
if (result[i] >= 10)
{
result[i - 1] += result[i] / 10;
result[i] %= 10;
}
}
// 打印结果
for (int i = 0; i < length1 + length2; i++)
{
std::cout << result[i];
}
std::cout << std::endl;
}
int main() { math_tool::getvalue('12', '12');
return 0;
}
这段代码的结果为什么是1440 该怎么修改内容:该段代码是一个实现两个字符串表示的整数相乘的函数。结果为1440是因为输入的两个字符串分别表示的整数是12和12,它们相乘的结果是144。但是在计算过程中,没有考虑进位的情况,所以结果是错误的。
要修改这段代码,需要在计算结果时考虑进位的情况。可以在计算result数组的时候,将每一位的进位加到下一位上。具体修改如下:
void math_tool::getvalue(const char *first, const char *second)
{
int length1 = strlen(first);
int length2 = strlen(second);
// 用于存储结果的数组,最大长度为 length1 + length2
int result[length1 + length2] = {0};
for (int i = 0; i < length1; i++)
{
for (int j = 0; j < length2; j++)
{
result[i + j] += (first[i] - '0') * (second[j] - '0');
}
}
for (int i = length1 + length2 - 1; i > 0; i--)
{
if (result[i] >= 10)
{
result[i - 1] += result[i] / 10;
result[i] %= 10;
}
}
// 打印结果
for (int i = 0; i < length1 + length2; i++)
{
std::cout << result[i];
}
std::cout << std::endl;
}
这样修改后,结果就会是正确的。
原文地址: https://www.cveoy.top/t/topic/o85J 著作权归作者所有。请勿转载和采集!