console.readline()的问题;在c#中,无论我输入什么数字,它都将它编号为49

时间:2015-06-05 22:18:26

标签: c#

我对c#完全不熟悉,这是我的第一个程序。

 namespace CPU_load {
    class Program {

        static void Main(string[] args) {
            Console.WriteLine("Welcome to the Jackson CPU monitor");
            Console.WriteLine("Press ESC at any time to exit");
            //instructions_1 = Console.WriteLine("Would you like the view the instructions (y/n)   ");
            Console.Write("How often would you like to take a reading?(in seconds)    ");
            interval = Console.Read();

            Console.WriteLine();
            Console.WriteLine(interval);

            interval_int1 = Convert.ToInt32(interval);
            //int interval_int = (int)interval;
            int interval_int_milliseconds = interval_int * 1000;

            Console.WriteLine("A reading will be taken every {0} seconds", interval_int1);

            Thread.Sleep(2500);
            PerformanceCounter perfCPUcount = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
            PerformanceCounter perfMEMcount = new PerformanceCounter("Memory", "Available MBytes");
            ConsoleColor oldColor = Console.ForegroundColor;

            while (true) {
                float cpuload = (int) perfCPUcount.NextValue();
                float memload = (int) perfMEMcount.NextValue();

                if (cpuload == 100) {
                    Console.ForegroundColor = ConsoleColor.Red;
                }


                if (cpuload <= 20) {
                    Console.ForegroundColor = ConsoleColor.Green;
                }

                Console.Write("CPU load {0}%                           ", cpuload);
                Console.ForegroundColor = oldColor;
                DateTime now = DateTime.Now;
                Console.WriteLine(now);
                Console.ForegroundColor = oldColor;

                if (memload <= 500) {
                    Console.ForegroundColor = ConsoleColor.Red;
                }

                if (memload <= 1500) {
                    Console.ForegroundColor = ConsoleColor.Green;
                }


                if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) break;

                Console.WriteLine("Available Memory {0}MB", memload);
                Thread.Sleep(1000);
            }
            Console.ForegroundColor = oldColor;
        }

        public static int interval_int {
            get;
            set;
        }

        public static int interval {
            get;
            set;
        }

        public static int interval_int1 {
            get;
            set;
        }
    }
 }

无论我输入什么号码,我总是在上面代码的第6行输出数字49。我不知道它为什么会发生它是一个CPU使用监视器,我想使用用户输入作为读取CPU使用之间的延迟。

1 个答案:

答案 0 :(得分:4)

您正在执行Console.Read();,它只读取单个字符并返回其ASCII值。

输出49的原因是因为49是1的ASCII值。

您需要使用Console.ReadLine()来输入输入的文本,然后使用int.TryParse之类的内容将文本转换为数字表示。