转换如何进行? [英] How the conversion is working?

查看:85
本文介绍了转换如何进行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参见代码段...

please see the code snippet...

str="44.22";
double d = Convert.ToDouble(str);
Console.WriteLine("the d val" + d);
int doll;
int cent;
doll=(int)d;
Console.WriteLine(doll);      //44
cent =(int)( (d - doll) * 100);
Console.WriteLine(cent);     //21


在"cent"的输出中为什么是21,为什么不是22.

如果我使用的是


In the output of ''cent'' why it is 21,why not 22.

if i am using

Convert.Int32((d-doll)*100);

,则输出将为22.

推荐答案

Richard MacCutchan 的解决方案2所述,十进制精度是浮点数和双精度数的问题.对于高精度decimal ,可以使用数据类型.
请检查以下代码.
As said in solution 2 by Richard MacCutchan decimal precision is a problem with float and double. For high precision decimal Data Type can be used.
Please check the following code.
string str="44.22";
decimal d = Convert.ToDecimal(str);
Console.WriteLine("the d val = " + d);
int doll;
int cent;
doll=(int)d;
Console.WriteLine(doll);      //44
cent =(int)( (d - doll) * 100);
Console.WriteLine(cent);     //22


这是有关使用floatdouble值的问题,由于在浮点值只是这些值的近似值,因此在这些值及其字符串表示形式之间进行转换时,您会并且会失去精度.

当使用精度要求很高的数字时,应仅使用整数.例如,当使用表示美元和美分的值时,应在小数点处拆分字符串,将其转换为整数,然后转换为美分的总数.当您希望显示任何值时,需要将其转换为它们的单独部分.
This is part of the problem of using float or double values, you can and will lose precision when converting between the values and their string representations, since floating point values are only approximations of the values.

When using numbers where accuracy is important you should use integers only. For example when using values representing dollars and cents you should split the string at the decimal point, convert both to integers and thence to total number of cents. When you wish to display any values you need to reconvert to their separate parts.


我有一个链接..
我刚开始阅读...
所以我无法得出结论...
但是我希望在阅读完完整的文档后,我们可以理解为什么它要打印此输出...

希望你会读...

如果您想了解知识,请完整阅读...

每位计算机科学家应了解的浮点运算法则 [ ^ ]
I got a link..
I just started reading...
So i cant able to conclude it...
But i hop after reading this complete doc, we can understand why it is printing this output...

Hope you will read it...

If you want knowledge,read it completely...

What Every Computer Scientist Should Know About Floating-Point Arithmetic[^]


这篇关于转换如何进行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆