使用字符串存储数字的长除法1 / N算法,太长时会创建符号/字母

问题描述

我正在尝试针对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,c);
                decimals = temp;
                printf("%s\n\n",decimals);
            }
        }
    }   
    free(decimals);
}

和CMD输出

enter image description here

是什么导致#字符出现?如果运行更长的时间,则会出现更多的随机字母/符号。

解决方法

我认为分配内存的方式就是问题所在。您最终将写出超过else语句中分配的内存量。该长度在不应该扩展的情况下。

?DayReference(vbSaturday,DateSerial(2020,8,22))
 22