[英]Find Minimum and Maximum values within a multi dimensional struct array
對於正在學習c#的學校項目,我正在制作一個數據收集控制台應用程序,該應用程序將保存4個不同位置的浮點條目以及時間/日期以及記錄該條目的用戶。 我需要使用多維結構數組。
我需要一個顯示值平均值,最小值和最大值以及第一個和最后一個日期的視圖。 我已經通過計算值並累加得出平均值,但是我不知道如何找到最小值和最大值。
我嘗試搜索並遇到了以下頁面: http : //www.dotnetperls.com/max我嘗試將這種語法實現到我的代碼中,但由於數組更加復雜,因此無濟於事。
它在我的整數測試中起作用:
class Program
{
static int[][] intarray = new int[4][] { new int[10], new int[10], new int[10], new int[10] };
static void Main(string[] args)
{
intarray[0][0] = 5;
intarray[0][1] = 3;
intarray[0][2] = 10;
intarray[0][3] = 4;
intarray[0][4] = 2;
Console.WriteLine(intarray[0].Max());
Console.ReadLine();
}
}
上面的代碼完美地顯示了數字10! :)
但是,當我嘗試使用struct數組將其實現到程序中時,它不起作用:
class Program
{
static byte location = 0;
static float entriesmin;
static float entriesmax;
static Entry[][] entriesarray = new Entry[4][] { new Entry[10], new Entry[10], new Entry[10], new Entry[10] };
struct Entry
{
public float value;
public string user;
public DateTime datetime;
}
static byte LoopEntries(bool display)
{
float runningtotal = 0;
byte entrycount = 0;
foreach (Entry entry in entriesarray[0])
{
if (entry.user != null)
{
if (display)
{
string ten;
if (entrycount == 9)
{
ten = " #";
}
else
{
ten = " #";
}
Console.WriteLine(ten + (entrycount + 1) + " " + entry.datetime + " " + entry.user + new string(' ', 16 - entry.user.Length) + entry.value);
}
runningtotal += entry.value;
entrycount += 1;
}
}
entriesmin = (entriesarray[location]).value.Min();
entriesmax = (entriesarray[location]).value.Max();
if (entrycount == 0 && display)
{
Console.WriteLine("No entries to show!");
}
return entrycount;
}
我需要在星期一交這個項目! 我真的希望有人能幫助我! ;)
您擁有的不是多維數組,而是數組數組(又稱鋸齒數組),但是您可以通過類似的方式來使用它們。
要遍歷數組數組,您需要一個循環:
foreach (Entry[] arr in entriesarray) {
foreach (Entry entry in arr) {
// ...
}
}
您可以使用Min
和Max
擴展方法來獲取每個內部數組的最小值和最大值,但是您仍然必須在這些值之間找到最小值和最大值。 無論如何,您已經在所有條目中進行循環以獲取平均值,因此您只需記錄找到的最小和最大值即可:
float runningtotal = 0;
int entrycount = 0;
float min = float.MaxValue;
float max = float.MinValue;
foreach (Entry[] arr in entriesarray) {
foreach (Entry entry in arr) {
runningtotal += entry.value;
entrycount++;
if (entry.value < min) {
min = entry.value;
}
if (entry.value > max) {
max = entry.value;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.