我的数组中的预定值与销售数字有关,但我想知道如何将其更改为接受用户对商店价值的输入。我见过一些接受用户输入的"for"循环,但我不知道它们是适用于锯齿状数组还是仅适用于多维数组;我也不理解它们背后的逻辑。我知道这是一个简单的概念,但我还是个初学者。
int[][] stores = {new int [] {2000,4000,3000,1500,4000},
new int [] {6000,7000,8000},
new int [] {9000,10000}};
double av1 = stores[0].Average();
double av2 = stores[1].Average();
double av3 = stores[2].Average();
double totalav = (av1 + av2 + av3) / 3;
Console.WriteLine("Region 1 weekly sales average is: {0}", av1);
Console.WriteLine("Region 2 weekly sales average is: {0}", av2);
Console.WriteLine("Region 3 weekly sales average is: {0}", av3);
Console.WriteLine("The total store average is: {0}", totalav);
处理此问题以允许用户输入数据的最佳方法可能是放弃数组,转而使用List<List<int>>
。为什么?因为List<T>
将动态增长。否则,您仍然可以使用数组,但必须具有固定的长度(或者用户必须首先提供这些长度)。
所以你可以这样做:
List<List<int>> stores = new List<List<int>>();
int storeNum = 0;
string input = "";
do
{
var store = new List<int>();
Console.WriteLine(string.Format("Enter sales for store {0} (next to go to next store, stop to finish)",storeNum++ ));
do
{
int sales = 0;
input = Console.ReadLine();
if (int.TryParse(input, out sales))
{
store.Add(sales);
}
// Note: we are ignoring invalid entries here, you can include error trapping
// as you want
} while (input != "next") // or whatever stopping command you want
stores.Add(store);
} while (input != "stop") // or any stopping command you want
// At this point you'll have a jagged List of Lists and you can use Average as before. For example:
var avg = stores[0].Average();
// Obviously, you can do this in a loop:
int total = 0;
for (int i=0; i<stores.Count; i++) // note lists use Count rather than Length - you could also do foreach
{
var avg = stores[i].Average();
Console.WriteLine(string.Format("Store {0} average sales: {1}", i, avg);
total += avg;
}
Console.WriteLine(string.Format("Overall Average: {0}", total / stores.Count));
您肯定可以用用户输入来填充stores
。有几种不同的方式。如果您想将stores
保持为锯齿状阵列,您必须首先了解阵列的大小。
Console.Write("Number of store groups: ");
int numberOfStoreGroups = int.Parse(Console.ReadLine());
int[][] stores = new int[numberOfStoreGroups][];
// Now loop through each group
for (int i = 0;i < numberOfStoreGroups;++i)
{
Console.Write("Number of stores in group {0}: ", i + 1);
int groupSize = int.Parse(Console.ReadLine());
stores[i] = new int[groupSize];
// Now loop through each store in the group
for (int j = 0;j < groupSize;++j)
{
Console.Write("Store number {0}: ", j + 1);
stores[i][j] = int.Parse(Console.ReadLine());
}
}
到那时你就完了。您的锯齿状阵列已填充。
不过,您可能会发现使用List<int>
而不是int
数组更容易。使用List<int>
,您不必担心预先确定大小。您可以简单地为其Add()
添加一个新编号。