【问题标题】:If i add 2 double data type value, the result is round off and print.How do i get the exact output in double?如果我添加 2 个双精度数据类型值,结果是四舍五入并打印。如何获得双精度输出?
【发布时间】:2016-10-25 10:10:05
【问题描述】:

我需要添加双精度值并显示结果。但是结果值是错误的。

class Program
{
    static void Main(string[] args)
    {
        int i = 4;
        double d = 4.0;
        string s = "HackerRank ";
        int i1 = 12;
        double d1 = 4.0;
        string s1 = "is the best place to learn and practice coding!";
        int sum = 0; string s2 = string.Empty;
        sum = sum+i + i1;
        s2 = s2 + s + s1;
        Console.WriteLine(sum);
        Console.WriteLine("{0}+{1}={2}",d,d1,(d+d1).ToString());
        Console.WriteLine(s2);
        Console.ReadLine();
    }
}

the output snapshot is here

我的预期输出是 4.0+4.0=8.0

但输出值是四舍五入。谁能提供这个问题的原因和解决方案?

【问题讨论】:

  • 对于小数精度使用小数!
  • 是的,这是一个很好的答案,但我的要求是只使用双精度。而不是小数。无论如何感谢您的回答。

标签: c# output user-defined-data-types


【解决方案1】:

试试这个

Console.WriteLine( String.Format("{0:0.0}", d + d2));

【讨论】:

    【解决方案2】:

    如果您想以 x.xx 格式显示输出,您可以使用:

    Console.WriteLine("{0:F2}+{1:F2}={2:F2}",d,d1,d+d1);
    

    【讨论】:

      【解决方案3】:

      在每个 double 上使用 ToString() 试试

      Console.WriteLine($"{d.ToString("G1")}+{d1.ToString("G1")}=(d + d1).ToString("G1")});
      

      【讨论】:

      • 谢谢。很好的答案。我会试试这些
      【解决方案4】:

      使用这个

      Console.WriteLine("{0:F}+{1:F}={2:F}",d,d1,d+d1);
      

      “F”是定点格式说明符。您还可以根据需要将“F”更改为“F2、F3 等”来指定所需的小数位数,或者将其保留为“F”,以便它可以根据变量返回输出。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-22
        • 1970-01-01
        相关资源
        最近更新 更多