我的数组中的预定值与销售数字有关,但是我想知道如何更改它以接受用户输入的商店价值。我已经看到一些接受用户输入的“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);
答案 0 :(得分:2)
最好处理这个以允许用户输入数据可能是放弃数组并改为使用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));
答案 1 :(得分:1)
您绝对可以使用用户输入填充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()
一个新号码即可。