【发布时间】:2019-10-07 19:54:51
【问题描述】:
我是编程新手,对如何在数组中显示值的索引号感到困惑。我希望能够键入一个随机数,如果我输入的数字在数组中,那么它应该告诉我该数字在数组中的位置(索引)是什么。
例如,如果我输入数字 6,并且 6 在我的数组中并且它的索引是 4,那么输出应该是“该数字存在,它在数组中位于 4”。我试过这样做,但我的代码与此相反,例如,如果我输入 6,它会查找索引 6 并输出与索引 6 对应的数字。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace searcharray
{
class Program
{
static void Main(string[] args)
{
int n = 10;
Random r = new Random();
int[] a;
a = new int[n + 1];
for (int i = 1; i <= n; i++)
a[i] = r.Next(1, 100);
for (int i = 1; i <= n; i++)
Console.WriteLine(" a [" + i + "] = " + a[i]);
Console.ReadLine();
Console.WriteLine("Enter a number: ");
int b = Convert.ToInt32(Console.ReadLine());
if (a.Contains(b))
{
Console.WriteLine("That number exists and the position of the number is: " + a[b]);
}
else
{
Console.WriteLine("The number doesn't exist in the array");
}
Console.WriteLine();
Console.ReadLine();
}
}
}
【问题讨论】:
-
Array.IndexOf 会给你索引或者-1如果没有找到。数组也是从零开始的,所以
a[0]将是 0(默认值),因为它从未设置为另一个值。如果要显示基于 1 的索引,只需在显示结果中添加 1,否则坚持使用基于 0 的索引。