如何计算 for 循环、并行数组中两个不同项目的平均值?

问题描述 投票:0回答:1

我试图提供两组不同数据的平均值。当我运行代码时,其他值(卡路里)没有显示任何值。

your text
总计 = 0.0
your text
卡路里= 0.0

your text
对于 z = 1 到 arraySize
your text
TextWindow.WriteLine(menuitem[z] + tab + "$" + PricePerLb[z] + tab + calsPerServing[u])
your text
总计=总计+pricePerLb[z]
your text
结束

your text
对于 u = 1 到 arraySize
your text
TextWindow.WriteLine(menuitem[z] + tab + "$" + PricePerLb[z] + tab + calsPerServing[u])
your text
卡路里 = 卡路里 + 每份卡路里数[u]
your text
结束

'平均价格

your text
avg = 总数 / 数组大小
your text
TextWindow.WriteLine("")
your text
TextWindow.WriteLine("") '平均卡路里
your text
avgCal = 卡路里 / Array.GetItemCount(calsPerServing)
your text
TextWindow.WriteLine("")
your text
TextWindow.WriteLine("")

your text
TextWindow.WriteLine("平均卡路里:")
your text
TextWindow.WriteLine("平均价格:" + avg)

python arrays for-loop average smallbasic
1个回答
0
投票

您可以通过将两个循环合并为一个来解决这个问题,如下所示:

total = 0.0
calories = 0.0

For z = 1 To arraySize
    TextWindow.WriteLine(menuitem[z] + tab + "$" + pricePerLb[z] + tab + calsPerServing[z])
    total = total + pricePerLb[z]
    calories = calories + calsPerServing[z]
EndFor

'price avg
avg = total / arraySize
TextWindow.WriteLine("")

'cal avg
avgCal = calories / arraySize
TextWindow.WriteLine("")

TextWindow.WriteLine("Average calorie: " + avgCal)
TextWindow.WriteLine("Average price: " + avg)
© www.soinside.com 2019 - 2024. All rights reserved.