我目前正在将长值写入文本文件,每当我将它们分成Console.WriteLine
或writeFile.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);
答案 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;