【发布时间】:2017-04-22 01:45:55
【问题描述】:
作为我课堂上编码挑战的一部分,我们必须编写代码来提供 10 种不同的任务。
在此任务中,我的目标是创建一个线性搜索算法,在数组中搜索特定项目,如果找到则显示其位置。
这是我当前的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linearsearch2
{
class Program
{
static void Main(string[] args)
{
var array = new int[] { 1, 31, 10, 9, 420, -5, 77, 420, 300, 99 }; //Sets up the array
var targetvalue = 77; //Establishes what number the search will attempt to find.
var targetpos = -1; //Establishes the position in the array of the target.
var targetnumber = 0; //Establishes the counter for the number of times the target appears.
bool found = false; //Decides wether to change the number or use a counter method.
var foundpositions = new int[] { }; //Establishes an array which will hold the positions of located items
for (var i = 1; i < array.Length; i++)
{
if (found == true && array[i] == targetvalue)
{
targetnumber = targetnumber + 1;
}
if (found == false && array[i] == targetvalue) //If the target value has not been found yet
{
foundpositions.Add(i); //This is the line i need help with. I dont know how to add a value to an array properly.
found = true;
}
}
if (targetpos != -1){ //If the target number was found
Console.WriteLine("The number " + targetvalue + " appeared " + targetnumber + " times, at positions " + foundpositions + "."); // Prints the final outcome.
}
else //If the target number was not found
{
Console.WriteLine("The number " + targetvalue + " did not appear in this array."); // Prints the final outcome.
}
}
}
}
我需要帮助的问题是第 31 行, foundpositions.Add(i);
我不知道正确向数组添加值的行,这似乎是导致问题的原因。 (在这一行中,我试图将搜索的当前位置添加到稍后将显示的数组中)
感谢您的帮助。此外,如果有任何其他明显的、明显的错误,请指出它们,我们将不胜感激。
【问题讨论】:
-
您能解释一下为什么要检查是否找到目标吗?这似乎没有必要。
标签: c# arrays linear-search