我正在做一些初学者工作在C#上,使用visual studio。我必须计算用户输入到数组中的最小数字。我需要编写代码来手动完成。这是我有什么相关的。将变量设置为数组中的第一个值 -
public partial class Form1 : Form
{
//Declare and initialise variables to be used in app.
int[] markArray = new int[10]; //Declare an array of integers to hold entered user values
int arrayPointer = 0; //Declare array pointer - This will be incremented after each function is carried out, so that the next user entered number will be placed in the next index position in the array.
int lowestMark = 0; //Declare lowest mark
private void buttonAdd_Click(object sender, EventArgs e) //on a button click within the app
{
try //Test value enter is number
{
markArray[arrayPointer] = Convert.ToInt32(textEntry.Text); //Take value from text box and place in array cell if it is a int
}
catch //Catch non ints
{
MessageBox.Show("You must enter a number "); //if not int display error messsage
}
int lowestMark = markArray[0]; // Set variable "lowestMark" to the value in the first position of the array.
for (int i = 0; i < 10; i++)
{
if (markArray[i] < lowestMark) // if there is an index with a value lower than the value assigned to "lowestMark"
{
lowestMark = markArray[i]; //Set this new lower value as the "lowestMark"
}
}
arrayPointer++; //Increment array pointer
}
所以无论哪种方式我已经与它摆弄的lowestMark
值始终是相同的值,我给它时,我声明。如果我在申报时输入set it to 100
,那么运行时就会显示为最低标记。所以它会出现这样的行,将其设置为数组中的索引0中的值什么也不做。即使通过输入10个数字来填充数组中的每个索引,它仍将读为0.我不知道为什么,这很奇怪,因为我试图做的事似乎很简单。
Enter a value into markArray
,在index
通过arrayPointer
决定,这starts at 0.
Set lowestMark
以在同一位置上的相同的值。递增arrayPointer,以便下一个值将被输入到索引1中。
该程序有一些其他的小函数,它在该按钮上单击时执行,但我已将它们移除以仅保留不起作用的东西
而不是try/catch使用int.TryParse()。例外情况不应用于流量控制。 –
面对这样的问题,我会给你最好的建议:按F5并逐步调试。 – rcdmk
我会在调试器中运行它,并确保变量值是您所期望的。我对你使用'arrayPointer'感到困惑,并怀疑是这个问题。 –