내 수업의 코딩 과제의 일환으로 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.
}
}
}
}
내가 foundpositions.Add (I)와, 라인 (31) 함께 도움이 필요한 문제;
배열에 값을 제대로 추가하는 줄을 모릅니다.이 문제가 원인 인 것 같습니다. (이 줄에서는 나중에 표시 할 배열에 검색의 현재 위치를 추가하려고합니다.)
감사합니다. 또한, 명백한 다른 눈에 띄는 오류가 있으면이를 지적 해 주시면 감사하겠습니다.
대상이 발견되었는지 확인하는 이유를 설명 할 수 있습니까? 이것은 불필요한 것으로 보인다. – JohnG