简体   繁体   English

如果我将2的double数据类型值相加,结果将四舍五入并打印出来。如何获得double的确切输出?

[英]If i add 2 double data type value, the result is round off and print.How do i get the exact output in double?

I need to add double values and display it result. 我需要添加双精度值并显示结果。 But the resulting value was wrong. 但是结果值是错误的。

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 输出快照在这里

My expected output is 4.0+4.0=8.0 我的预期输出是4.0 + 4.0 = 8.0

But the output value is roundoff. 但是输出值是四舍五入的。 Can anyone provide the reason and solution for this question? 谁能提供这个问题的原因和解决方案?

尝试这个

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

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

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

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

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

Use this 用这个

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

"F" is Fixed-Point Format Specifier. “ F”是定点格式说明符。 You can also specify the desired number of decimal places by changing the "F" to "F2,F3 and so on" as per your requirement or leave it as "F" so that it can return output according to the variable. 您还可以根据需要通过将“ F”更改为“ F2,F3等”来指定所需的小数位数,或者将其保留为“ F”,以便它可以根据变量返回输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM