作爲我課程中編碼挑戰的一部分,我們必須生成代碼以提供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)的問題;
我不知道該行爲數組正確添加值,這似乎是導致問題的原因。 (在這一行中,我試圖將搜索的當前位置添加到將在稍後顯示的數組中)
感謝您的幫助。此外,如果還有其他明顯的,明顯的錯誤,指出他們將不勝感激。
你能解釋爲什麼你要檢查目標是否被發現?這似乎沒有必要。 – JohnG