长在字符串中分割时打印错误的值

时间:2014-03-18 02:24:59

标签: c# printing long-integer

我目前正在将长值写入文本文件,每当我将它们分成Console.WriteLinewriteFile.WriteLine时,值会更改并变为0,但是当我打印变量时:inUse ,tot和phav,它打印一个长值。可能是什么问题?

我所做的调试方法是将它转换为字符串,计算字符串外部的除法,放置ToString并在计算部分中删除它。

            long phav = PerformanceInfo.GetPhysicalAvailableMemoryInMiB();
            long tot = PerformanceInfo.GetTotalMemoryInMiB();
            decimal percentFree = ((decimal)phav / (decimal)tot) * 100;
            decimal percentOccupied = 100 - percentFree;
            long inUse = tot - phav;

            logTextFile.WriteLine("Created File Size: " + Math.Round(size / 1024 / 1024) + "MB");
            String one = "Physical Memory Size: " + (tot / 1024 / 1024).ToString() + "MB";
            String two = "Physical Memory In Use: " + (inUse / 1024 / 1024).ToString() + "MB (" + Math.Round(percentOccupied, 2) + "%)";
            String three = "Physical Memory Available: " + (phav / 1024 / 1024).ToString() + "MB (" + Math.Round(percentFree, 2) + "%)";

            Console.WriteLine(phav);
            Console.WriteLine(tot);
            Console.WriteLine(inUse);

            Console.WriteLine(one);
            Console.WriteLine(two);
            Console.WriteLine(three);

            logTextFile.WriteLine(one);
            logTextFile.WriteLine(two);
            logTextFile.WriteLine(three);

1 个答案:

答案 0 :(得分:1)

你在下面的计算中丢失了小数点后的值,所以结果最终为0.(当你将整数和长整数除以小数和双精度时会发生什么。)< / p>

(inUse / 1024 / 1024)

将整数更改为小数以保留结果的小数部分:

(inUse / 1024m / 1024m)

或者更改代码段中的前五个变量,使它们全部为十进制类型,然后您可以保留1024原样:

 decimal phav = PerformanceInfo.GetPhysicalAvailableMemoryInMiB();
 decimal tot = PerformanceInfo.GetTotalMemoryInMiB();
 decimal percentFree = ((decimal)phav / (decimal)tot) * 100;
 decimal percentOccupied = 100 - percentFree;
 decimal inUse = tot - phav;