[英]Find the highest number in array , using while or for?
Please ai have a Questions , I need find the higghest value in array. 请给我一个问题,我需要在数组中找到最大的值。 To the array will people write name (textbox1) and money (texbox2). 人们会在数组中输入名称(textbox1)和货币(texbox2)。 I have 2 buttons first button is save to the array and second write the name with the biggest money. 我有2个按钮,第一个按钮保存到数组中,第二个用最大的钱写下名字。
Code for save: 保存代码:
string[] name = new string[50];
int items = 0;
int[] money = new int[50];
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
Convert.ToInt32(textBox2.Text);
}
catch
{
name[items] = textBox1.Text;
money[items] = Int32.Parse(textBox2.Text);
items++;
}
}
And to the button2 need search the biggest value and write name! 并向button2需要搜索最大的值并写下名称! Please help me 请帮我
private void button2_Click(object sender, EventArgs e)
{
int maxIndex = 0;
for(int i = 0; i < 50; i++)
{
if (money[i] > money[maxIndex])
maxIndex = i;
}
MessageBox.Show(name[maxIndex] + " has biggest value " + money[maxIndex]);
}
To get the Max int from your array you can use IEnumerable.Max : 要从数组中获取Max int,可以使用IEnumerable.Max :
money.Max();
But there could be more than one name with the same high money value, perhaps you need to handle this also, I think Dictionary would be your best option 但是可能会有不止一个名字具有相同的高额货币价值,也许您也需要处理这个问题,我认为Dictionary将是您的最佳选择
private Dictionary<string, int> Names = new Dictionary<string, int>();
private void button1_Click(object sender, EventArgs e)
{
int value = 0;
if (int.TryParse(textBox2.Text, out value))
{
if (!Names.ContainsKey(textBox1.Text))
{
Names.Add(textBox1.Text, value);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
if (Names.Any())
{
int maxMoney = Names.Max(v => v.Value);
var names = Names.Where(k => k.Value.Equals(maxMoney));
foreach (var name in names)
{
// Names with the highest money value
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.