私のクラスのコーディング課題の一部として、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