首页 技术 正文
技术 2022年11月14日
0 收藏 478 点赞 4,577 浏览 794 个字

问题复现步骤:
1) 输入字符串:
{
    “V”:0.12345678
}

2) 字符串转成cJSON对象

3) 调用cJSON_Print将cJSON对象再转成字符串
4) 再将字符串转成cJSON对象
5) 保留8位精度方式调用printf打印值,输出变成:0.123456

问题的原因出在cJSON的print_number函数:
static char *print_number(cJSON *item)
{
    char *str;
    double d = item->valuedouble;
    if (fabs(((double) item->valueint) – d) <= DBL_EPSILON && d <= INT_MAX
                    && d >= INT_MIN)
    {
        str = (char*) cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */
        if (str)
            sprintf(str, “%d”, item->valueint);
    }
    else
    {
        str = (char*) cJSON_malloc(64); /* This is a nice tradeoff. */
        if (str)
        {
            if (fabs(floor(d) – d) <= DBL_EPSILON)
                sprintf(str, “%.0f”, d);
            else if (fabs(d) < 1.0e-6 || fabs(d) > 1.0e9)
                sprintf(str, “%e”, d);
            else
                sprintf(str, “%f”, d);
        }
    }
    return str;
}

最后一个sprintf调用没有指定保留的精度,默认为6位,这就是问题的原因。
注:float的精度为6~7位有效数字,double的精度为15~16位。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,955
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,774