【发布时间】:2020-12-11 21:07:56
【问题描述】:
我正在尝试专门针对 1/N 的情况制定一个长除法算法。我已经让代码正常工作,但是当存储数字的字符串长度达到 ~>20 位时,数据类型正在做一些“时髦的事情”。
您可以更改 b 变量来测试任何其他分数。
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int a = 1;
int b = 666;
int c = 0;
int d = 1;
int z = 0;
char *decimals = "0.";
size_t len = 2;
while (d>0)
{
printf("a: %d ",a);
printf("b: %d ",b);
printf("c: %d ",c);
printf("d: %d\n",d);
if(a<b)
{
a = a*10;
if(a<b)
{
len = len + 2;
char *temp = calloc(len, sizeof(char));
sprintf(temp, "%s%d",decimals,z);
decimals = temp;
printf("%s\n\n", decimals);
}
else
{
c = a/b;
d = a-b*c;
a = d;
char *temp = calloc(len, sizeof(char));
sprintf(temp, "%s%d",decimals,c);
decimals = temp;
printf("%s\n\n", decimals);
}
}
}
free(decimals);
}
还有 CMD 输出:
是什么导致#字符出现?如果运行时间更长,则会出现更多随机字母/符号。
【问题讨论】:
-
它发生在最长的字符串上,这表明数组溢出。您可以从
sprintf(temp, "%s%d",decimals,z);(输出字节数)收集返回值并将其与calloc分配进行比较,不要忘记字符串终止符的空间。