GTK+中文社区(gtk.awaysoft.com)

 找回密码
 马上加入

QQ登录

只需一步,快速开始

查看: 3437|回复: 4

g_ascii_dtostr ( )转换字符串的问题

[复制链接]

该用户从未签到

发表于 2012-4-28 23:44:39 | 显示全部楼层 |阅读模式
最近在做一个项目,使用gtk+2.0和linux环境开发的,其中用了g_ascii_dtostr ( )将float浮点数转换为字符串,考虑精度问题,所以每个浮点数都有一个误差值,大小为0.000005,并取三位有效数字,但是当需要转换的值为0.0的时候,加上误差值后,本来期待转换结果为0,结果却显示了5.00,而且只取误差值的有效数字,请问有高手知道何解么?经过测试,对于g_ascii_dtostr ( )这个函数,只要是0.0000X(前面n个0)的浮点数,转换后只会显示X。怀疑这是不是g_ascii_dtostr ( )的bug来的?有更好的代替方法么?

该用户从未签到

发表于 2012-4-29 19:57:47 | 显示全部楼层
直接用sprint 不行吗

该用户从未签到

发表于 2012-4-29 20:48:54 | 显示全部楼层
试了下没有你所说的
#include <stdio.h>
#include <glib.h>
#include <memory.h>

int main(int argc,char *argv[])
{
   
    gdouble gd;
    gd=0.0002;
    gchar buf[10];
    memset(buf,0,10);
    g_ascii_dtostr(buf,10,gd);
    printf("%s\\n",buf);

    return 0;
}

输出为  
0.0002000

该用户从未签到

 楼主| 发表于 2012-5-1 14:26:31 | 显示全部楼层

回 zhangjin9989 的帖子

zhangjin9989:试了下没有你所说的
#include <stdio.h>
#include <glib.h>
#include <memory.h>

....... (2012-04-29 20:48) 
前面再加个0试试。

该用户从未签到

 楼主| 发表于 2012-5-1 14:27:02 | 显示全部楼层
#include <stdio.h>
#include <stdlib.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <gdk/gdkkeysyms.h>
  /*  *   */
int main(int argc, char** argv)
{
         gtk_set_locale ();
         gtk_init (&argc, &argv);
         int len=10;
         float a = 0.0;
         gchar textAllFlag[10];
         a=0.55555555;
         g_ascii_dtostr(textAllFlag,len,a);
        printf("text:%s while a=%f\\n",textAllFlag,a);
         a=0.05555555;
         g_ascii_dtostr(textAllFlag,len,a);
        printf("text:%s while a=%f\\n",textAllFlag,a);
        a=0.00111111;  
       g_ascii_dtostr(textAllFlag,len,a);
        printf("text:%s while a=%f\\n",textAllFlag,a);  
       a=0.00011111;
       g_ascii_dtostr(textAllFlag,len,a);
        printf("text:%s while a=%f\\n",textAllFlag,a);
        a=0.00005555;  
        g_ascii_dtostr(textAllFlag,len,a);
        printf("text:%s while a=%f\\n",textAllFlag,a);
         a=0.00000555;
         g_ascii_dtostr(textAllFlag,len,a);
         printf("text:%s while a=%f\\n",textAllFlag,a);
         a=0.00000055;
         g_ascii_dtostr(textAllFlag,len,a);
         printf("text:%s while a=%f\\n",textAllFlag,a);
         return 0;
}

运行结果:

text:0.5555555 while a=0.555556
text:0.0555555 while a=0.055556
text:0.0011111 while a=0.001111
text:0.0001111 while a=0.000111
text:5.5550000 while a=0.000056
text:5.5499999 while a=0.000006
text:5.4999998 while a=0.000001
*滑块验证:
您需要登录后才可以回帖 登录 | 马上加入

本版积分规则

申请友链|Archiver|小黑屋|手机版|GTK+中文社区 ( 粤ICP备13080851号 )

我要啦免费统计

GMT+8, 2024-5-2 12:30 , Processed in 0.020548 second(s), 7 queries , Redis On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表