我有一個文本框來寫陣列的位置和一個文本框來寫那個位置的值。每次我想添加一個值和一個位置時,我都會單擊按鈕 btnStoreValue
我為另一個比較兩個數字并回傳最大的練習創建了一個函式 (CompareTwoNumbers)
使用該函式并避免使用像 > 和 < 這樣的比較字符我應該得到陣列的最大值
public partial class Form1 : ExerciseArray
{
int[] numbers = new int[10];
private int CompareTwoNumbers(int i, int j)
{
if (i < j)
{
return j;
}
return i;
}
private void btnBiggestValue_Click(object sender, EventArgs e)
{
//int n=1;
int counter = 0;
int highestPosition = CompareTwoNumbers(0, 1);
for(int i=0; i<10; i ){
//int j = CompareTwoNumbers(numbers[i], numbers[i 1])
//n = CompareTwoNumbers(numbers[n], numbers[i 1]
counter = CompareTwoNumbers(highestPosition, i);
}
txtBiggestValuePosition.Text= n.ToString();
txtBiggestValue.Text=numbers[n].ToString();
}
我嘗試了多種方法,使用了多個變數,我嘗試將其寫在紙上以試圖更好地理解事物,但我被困住了。我不知道如何使用我在上一個練習中創建的函式找到該值(假設我創建的函式是正確的)
uj5u.com熱心網友回復:
所以,你的問題的核心部分是你想知道如何使用你的輔助函式在陣列中找到最大的數字CompareTwoNumbers,然后找出最大數字的值和位置是什么。
根據我上面的理解,您的框架幾乎設定正確。
首先,CompareTwoNumbers 應該更新為回傳一個布林值。這樣做可以讓您有條件地更新持有最大數值和位置的變數。
private int CompareTwoNumbers(int i, int j)
{
if (i < j)
{
return true;
}
return false;
}
要知道(未排序的)陣列中的最大值是多少,您需要遍歷每個值。這樣做時,您需要跟蹤最大值的值和位置,只有在找到更大的值時才更新它。
private void btnBiggestValue_Click(object sender, EventArgs e)
{
// Store the bigget number's index and value
// We start with the first index and corresponding
// value to give us a starting point.
int biggestNumberIndex = 0;
int biggestNumber = numbers[0];
// Iterate through the array of numbers to find
// the biggest number and its index
for(int i=0; i<10; i )
{
// If the current number is larger than the
// currently stored biggest number...
if(CompareTwoNumbers(biggestNumber, numbers[i])
{
// ...then update the value and index with
// the new biggest number.
biggestNumber = number[i];
biggestNumberIndex = i;
}
}
// Finally, update the text fields with
// the correct biggest value and biggest
// value position.
txtBiggestValuePosition.Text= biggestNumberIndex.ToString();
txtBiggestValue.Text=numbers[biggestNumberIndex].ToString();
}
uj5u.com熱心網友回復:
這使用元組從同一方法中為您提供最大索引和最大值:
public (int, int) FindMaxValue(int[] items)
{
int maxValue = items[0];
int maxIndex = 0;
for(int i=1;i<items.Length;i )
{
if (items[i] > maxValue)
{
maxValue = items[i];
maxIndex = i;
}
}
return (maxIndex, maxValue);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/436554.html
