在数字数组中查找一个或多个数字

在数字数组中查找一个或多个数字

本文介绍了在数字数组中查找一个或多个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我要在控制台中键入一个数字,然后在 numb中显示小于它的所有数字数组。



Hi
I''m going to type in a number in the Console and then display all the numbers that are less than it in the numb array.

int[] numb = { -9, -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 8, 9 };

            Console.Write("pick a number: ");
            int v = int.Parse(Console.ReadLine());
            int t = 0;
            for (int x = 0; x < numb.Length; x++)
            {
                if (v > numb[x])
                    t = numb[x];
            }
            Console.Write("Your num under is: " + t);

            Console.ReadLine();





此代码仅显示一个数字。如何更改它以显示小于输入值的数字?



This code only only displays one number. How do I change it to display the numbers less than the entered value?

推荐答案

int[] numb = { -9, -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 8, 9 };

Console.Write("pick a number: ");
int v = int.Parse(Console.ReadLine());
int t = 0;
foreach (int n in numb)
{
    if (v > n)
    {
        t = n;
    }
}
Console.Write("Your num under is: " + t);

Console.ReadLine();

看看它读起来有多容易?

我做的另一个改变是在if语句周围加上大括号。当你开始使用时,总是使用括号是个好主意,即使你不需要它们 - 它可以让你以后在必须做出改变时更轻松。相信我:我花了好几个小时试图找出为什么我的代码不起作用才发现如果我把括号插入其中就显得太明显......:笑:



那么,你能看到你要做什么吗?

See how much easier it is to read?
The other change I made is to add curly brackets around the if statement. While you are getting started, it''s a good idea to always use brackets, even if you don''t need them - it can make your life a lot easier later when you have to make changes. Trust me on this: I spent hours trying to work out why my code didn''t work only to find that if I''d put brackets in it would have been sooooo obvious...:laugh:

So, can you see what you have to do?


int[] t;



在循环中你需要调整 t 数组...



[]



;)


Inside a loop you need to resize t array...

How to resize array in C#?[^]

;)


这篇关于在数字数组中查找一个或多个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 13:14