double2str函数(不使用库函数)

本文介绍如何实现一个double2str函数,用于将双精度浮点数转换为字符串,确保结果精确无误,即使在编译器数据精度问题下也能得到正确的小数点后位数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前在《 带参数的main函数 》一文小结中提到将double型数据转化为字符串(double2str函数),因为编译器数据精度的原因导致得出的字符串最后一位有误差,现在本文将误差补全,输出精准的字符串。
注:该程序得出的字符串省略了小数点

#include<stdio.h>
#include<math.h>
int main()
{
    char ch;    //循环结束标志
    double a;
    int point_num;     //精度(小数位数)
    double accuracy;   //精度(10^(-n))

    do
    {
        printf("输入待转换的double数据:");
        scanf("%lf",&a);
        printf("输入精度(几位小数):");
        scanf("%d",&point_num);
        accuracy=1/pow(10,point_num);    //精度转换为小数形式,如精度为4,accuracy=0.0001

        int i=0;
        int count=0;
        char str[10];
        int n,k;
        double judge;
        n=(int)a;
        while(1)
        {
            judge=n/pow(10,count);
            if(judge<accuracy)
            {
                if(n==9)    //精确位后一位是9,那就存在估读,精确位加1
                    str[i-1]=(k+1)%10+'0';
                break;
            }
            k=n;    //循环前数据留底
            str[i]=n%10+'0';
            count++;
            n=(int)(a*pow(10,count))%10;
            i++;
        }
        str[i]='\0';
        printf("a = %lf\t字符串:%s\n",a,str);


        fflush(stdin);
        printf("输入y/Y继续... ");
        ch=getchar();
        if(ch=='y'||ch=='Y')
            continue;
        else
            break;
    }
    while(1);
    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值