且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从用户控制台应用程序C#获取输入

更新时间:2023-02-17 21:52:25

int num = Convert.ToInt32(Console.ReadLine());



这一行只会转换一个数字,因为这是你要求它做的。您应该通过以下方式处理多个数字:


This line will only convert a single number, since that is what you have asked it to do. You should deal with multiple numbers by something like:

string[] numbers = Console.ReadLine().split(" ");
foreach (string num in numbers)
{
    int num = Convert.ToInt32(num);
    // test for less or not
}



注意***使用 TryParse 而不是转换以允许这种情况当用户键入无效字符时。


Note it is better to use TryParse rather than Convert to allow for the case when the user types invalid characters.


引用:

但是当我只输入1时这就像例如如果我输入9号码然后消息显示更少的号码,当我输入12然后消息显示不小于数量



我想要的地方

i输入10个数字并从该程序中识别哪些数字小于10

but this work like that when i enter only 1 e.g. if i enter 9 number then message display less number and when i enter 12 then message display Not less than num

where as i want
i input 10 numbers and from that program identifies which numbers are less than 10

您的代码完全按照您的要求执行。

您怎么可能不理解代码在做什么?这是你的代码吗?



你应该学会尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - ***,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - A初学者指南 [ ^ ]



调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。

Your code is doing exactly what you requested.
How is it possible that you don't understand what the code is doing ? Is it your code ?

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.


我会解决用这种方式编辑:



I would have solved it this way:

namespace check_Numbers
{
    class Program
    {
        static void Main(string[] args)
        {    
            string[] seperators = {",", " ", ";", "."};
            int num2;
            Console.WriteLine("Input numbers over 10:");

            string[] splitArray = Console.ReadLine().Split(seperators, StringSplitOptions.RemoveEmptyEntries);
            foreach (string num in splitArray)
            {

            If(Int32.TryParse(num, out num2) == true)
            {
                if (num2 < 10)
                {
                    Console.WriteLine(num + " is smaller than 10");
                }
            }
            else
            {
                Console.WriteLine(num + " is not a f***ing number...");
            }
            }
        }
    }
}