直接上源码:
#include <stdio.h>
#include <stdlib.h>
char* real_mult(const char* a, const char* b) {
int i, j, k, m, n, len_a, len_b;
len_a = strlen(a);
len_b = strlen(b);
int* res_p;
char* c;
res_p = (int*)malloc((len_a + len_b) * sizeof(int));
if (!res_p) {
printf((const char*)"malloc int[%d] fail!\n", len_a + len_b);
for ( ; ; );
}
for (i = len_a + len_b - 1; i >= 0; i--) {
res_p[i] = 0;
}
for (i = 0; i < len_a; i++) {
for (j = 0; j < len_b; j++) {
k = i + j + 1;
res_p[k] += (a[i] - '0') * (b[j] - '0');
}
}
res_p[0] = 0;
for ( ; k > 0; k--) {
res_p[k - 1] += res_p[k] / 10;
res_p[k] %= 10;
}
for (j = 0; j < len_a + len_b; j++) {
if (res_p[j] != 0) {
break;
}
}
c = (char*)malloc((len_a + len_b + 1 - j) * sizeof(char));
if (!c) {
printf((const char*)"malloc char[%d] fail!\n", len_a + len_b + 1 - j);
for ( ; ; );
}
for (i = 0; i < len_a + len_b - j; i++) {
c[i] = (char)(res_p[i + j] + '0');
}
free(res_p);
c[i] = '\0';
return c;
}
char* mult1(char* a, const char* b) {
char* c = real_mult((const char*)a, b);
free(a);
return c;
}
char* order(int n) {
char temp[16];
char* res = (char*)"1";
for ( ; n > 1; n--) {
sprintf((char*)temp, "%d", n);
res = mult1(res, (const char*)temp);
}
return res;
}
int main(int argc, const char* argv[]) {
char* c;
c = order(20000);
printf("%s\n", c);
free(c);
return 0;
}
测试结果比对:
离线
win系统和linux还是有些细微差异吧
离线
------------------------
错不在这!
而是这里
https://whycan.cn/files/members/334/1.png
改为这样:char* order(int n)
{
char temp[16];
char* res = (char*)"1";//删除
char* res = (char*)malloc(32); //改正后
for ( ; n > 1; n--)
{
sprintf((char*)temp, "%d", n);
res = mult1(res, (const char*)temp);
}
return res;
}就可以了。
确实是这个BUG,疏忽了
离线