我有程序代码,它工作正常,除了几行,程序必须找到最小的值并打印出来。
我有字符串字段/框“fieldEvidence.WorkingYears”。用户必须写0到40之间的数字。 用户可以放置最多10个值或更少(十个人)。程序必须在控制台中写出“fieldEvidence.WorkingYears”中最低的walue 如果值相同(比如2次'30'),程序必须同时写两个。
我现在有一些代码,但它没有以正确的方式工作,我应该改变什么?
static void WorkingAge(Evidence[] fieldEvidence)
{
int maxYears = 40;
int counter = 0;
for (int i = 0; i < fieldEvidence.Length; i++)
{
if (maxYears > fieldEvidence[i].WorkingYears)
{
maxYears = fieldEvidence[i].WorkingYears;
}
}
//10 times for loop
for (int i = 0; i < 10; i++)
{
if (maxYears == fieldEvidence[i].WorkingYears)
counter++;
}
//if there is more than just one with the same value
if (counter > 1)
{
for (int i = 0; i < fieldEvidence.Length; i++)
{
if (maxYears == fieldEvidence[i].WorkingYears)
{
Console.WriteLine("Working years:{0}, fieldEvidence[i].WorkingYears);
}
}
}
else
{
for (int i = 0; i < fieldEvidence.Length; i++)
{
if (maxYears == fieldEvidence[i].WorkingYears)
{
Console.WriteLine("Working years:{0}, fieldEvidence[i].WorkingYears);
}
}
}
}
实施例 用户输入:40,30,23,14,34 产出:工作年限:14
示例2 用户输入:40,23,14,14,34 产出:工作年限:14,14
答案 0 :(得分:1)
我建议您使用LINQ - 非常简单:
var example = new[]{40,30,23,14,34}.Select(year => new Evidence(year)).ToList();
var lowestVal = example.Min(x => x.WorkingYears);
var result = example.Where(x => x.WorkingYears == lowestVal)
.Select(x => x.WorkingYears);
Console.WriteLine("Working years: " + string.Join(", ", result));
答案 1 :(得分:0)
static void WorkingAge(Evidence[] fieldEvidence)
{
// make a counter for the number of equal min's found
int counter = 1;
// start with min equal to the first age in the array
int min = fieldEvidence[0];
// loop through array to find a possible new min
for (int i = 1; i < fieldEvidence.Length; i++) {
// if value < min, set min to this value and reset counter to 1
if (fieldEvidence[i].WorkingYears < min) {
min = fieldEvidence[i].WorkingYears;
counter = 1;
}
// if value equal to min, increase counter
else if (fieldEvidence[i].WorkingYears == min)
counter++;
}
// create your output string starting with the min
string output = min.ToString();
// loop "counter" times to add multiple identical mins to string
for (int i = 1; i < counter; i++) {
output = output + ", " + min;
}
// output the string
Console.WriteLine("Working years: " + output);
}