Domanda

I am currently writing long values to a text file, and whenever I divide and place them in a Console.WriteLine or writeFile.WriteLine the value changes and turns into 0, but when I print the variables: inUse, tot and phav, it prints a long value. What could be the problem?

The debugging methods I did are transfering it to a string, computing the division outside the string, place ToString and removing it in the computation part.

            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);
È stato utile?

Soluzione

You're losing the value after the decimal point in the following calculation, so the result ends up being 0. (That's what happens when you divide integers and longs instead of decimals and doubles.)

(inUse / 1024 / 1024)

Either change the integers to decimals to retain the decimal portion of the result:

(inUse / 1024m / 1024m)

Or change those first five variables in your code snippet so they're all decimal type, and then you can leave 1024 as is:

 decimal phav = PerformanceInfo.GetPhysicalAvailableMemoryInMiB();
 decimal tot = PerformanceInfo.GetTotalMemoryInMiB();
 decimal percentFree = ((decimal)phav / (decimal)tot) * 100;
 decimal percentOccupied = 100 - percentFree;
 decimal inUse = tot - phav;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top