本文介绍了解析浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 以下是代码: #include< stdio.h> #include< stdlib.h> int main(无效) { 浮动f; int part1,part4; 浮动第2部分; char part3 [6]; char s [] =" 1234.56abc 903"; char * p; sscanf(s,%2d%5e%5s%d,& part1,& part2,& part3,& part4); printf(" parse string:%s \ n",s); printf(" part1 =%d \ n",part1); printf (part2 =%f \ n,第2部分); printf(" part3 =%s \ n",part3); printf(" ; part4 =%d \ n",part4); 返回0; } 这里结果是: 解析字符串:1234.56abc 903 part1 = 12 part2 = 34.560001 part3 = abc part4 = 903 问题是为什么part2是34.560001,我希望这个数字是34.56。 是有一种方法我可以得到34.56吗? 谢谢。 解决方案 如果你对`part3`使用`double`(并改变`sscanf()`来使用 "%5le"而不是'%5e")你会得到你的''正在寻找 - 这个特殊情况下的这个特殊情况。但是,请记住,并非所有数字都可以在浮点运算中完全表示,因此您将会发现存储的内容不是您所期望的情况。 如果你真的需要精确的表示,请寻找支持无限精度的库 。 - MSDOS并没有像在一夜之间那么糟糕 - 花了十多年时间才开始小心开发。 ( dm******@aix1.uottawa.ca ) < http://clc-wiki.net/wiki/Introduction_to_comp.lang.c> 如果这是某些特定情况 - 那么...... printf(" part2 =%。2f \ n",part2) ; 并看到弗拉基米尔的评论! - ======= ======= 不是学生 ============== Here is the code:#include <stdio.h>#include <stdlib.h>int main(void){float f;int part1, part4;float part2;char part3[6];char s[]="1234.56abc 903";char *p;sscanf(s, "%2d%5e%5s%d", &part1, &part2, &part3, &part4);printf("parse string: %s\n", s);printf("part1=%d\n", part1);printf("part2=%f\n", part2);printf("part3=%s\n", part3);printf("part4=%d\n", part4);return 0;}Here is the result:parse string: 1234.56abc 903part1=12part2=34.560001part3=abcpart4=903question is why part2 is 34.560001, I expect this number to be 34.56.Is there a way I can get exact 34.56?Thanks. 解决方案If you use `double` for `part3` (and change `sscanf()` call to use"%5le" instead of "%5e") you will get what you''re looking for -- inthis particular case. However, bear in mind that not all numbers areexactly representable in floating point arithmetic, hence you''llalways find cases where what is stored is not what you expect.If you really, really need exact representation, look for librariesthat support infinite precision.--"MSDOS didn''t get as bad as it is overnight -- it took over ten yearsof careful development."(By dm******@aix1.uottawa.ca)<http://clc-wiki.net/wiki/Introduction_to_comp.lang.c>If this is some specific case - then...printf("part2=%.2f\n", part2);and see Vladimir''s comments!--==============Not a pedant============== 这篇关于解析浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-04 03:54