如何写和读取精确的双值?

时间:2018-05-15 07:53:09

标签: c# streamreader streamwriter readlines

我想将双重值写入文件:0\n0.1\n0.2\n0.3,但在某些值中,我无法写出确切的X.X值,错误:5.999\n6.099\n6.199,所以如何我可以写和读取确切的X.X值吗?

//stage 1: write value to file
using (StreamWriter sw = new StreamWriter(@"data.txt"))
{
    for (double d = 0; d < 100; d += 0.1)
    {
        sw.WriteLine(d);
    }
}

//stage 2: read value from file and set to list
foreach (string s in File.ReadLines(@"data.txt"))
{
    list.Add(Convert.ToDouble(s));
}

//stage 3: compare value from list and iteration
int iMatchCount=1;
for (double d = 0; d < 100; d += 0.1)
{
    if (list.Contains(d))
    {
        Console.WriteLine("Match" + iMatchCount++ + ": " + d);
    }
}
Console.Read();

0 个答案:

没有答案