在C#0.1的印刷增量 [英] Printing increments of 0.1 in c#

查看:76
本文介绍了在C#0.1的印刷增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即时通讯目前阅读代码完成由史蒂夫·麦康奈尔,特别是295页的浮点数

Im currently reading Code Complete by Steve McConnell, specifically page 295 on floating-point numbers.

当我跑到下面的代码:

        double nominal = 1.0;
        double sum = 0.0;

        for (int i = 0; i < 10; i++)
        {
            sum += 0.1;
            Console.WriteLine("sum: " + sum.ToString());
        }

        if (equals(nominal,sum))
        {
            Console.WriteLine("Numbers are the same");
        }
        else
        {
            Console.WriteLine("Numbers are different");
        }



我打印出
中的 0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
号不同

为什么我没有得到这是假设发生的输出?
,即:
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.79999999999999999
0.89999999999999999
0.99999999999999999
号不同

How come I didn't get the output that is suppose to happen? ie: 0.1 0.2 0.30000000000000004 0.4 0.5 0.6 0.7 0.79999999999999999 0.89999999999999999 0.99999999999999999 Numbers are different

是C#四舍五入的数字时,我做的隐式转换,从双串?我是这么认为的,因为当我通过调试应用程序和步骤,循环,我可以看到非终端重复的十进制数。你有什么感想?我说得对还是错?

Is C# rounding numbers when I do an implicit conversion from double to string? I think so because when i debug the application and step through the for loop, i can see the non-terminating repeating decimal numbers. What do you think? Am i right or wrong?

推荐答案

double.ToString()使用如精度,默认为15位小数的一般格式未标明。所以它做一点四舍五入这就是为什么你看到你所看到的。例如0.89999999999999999,你在你的问题中指定的17位小数。你可以通过做真正看到整个数 sum.ToString(G17)

double.ToString() uses the general format which defaults to 15 decimal places if the precision is not specified. So it does do a little rounding which is why you're seeing what you're seeing. For example 0.89999999999999999 which you specified in your question is 17 decimal places. You could actually see the entire number by doing sum.ToString("g17").

您可以找到。净的标准数字格式字符串和这里的默认精度: http://msdn.microsoft .COM / EN-US /库/ dwhawy9k(VS.80)的.aspx

You can find .net's Standard Numeric Format Strings and their default precision here: http://msdn.microsoft.com/en-us/library/dwhawy9k(VS.80).aspx

这篇关于在C#0.1的印刷增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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