1

我昨天刚开始接触 Nim。我的目标是计算表达式 b[i]/a[i] 中值的平均值。我尝试使用数学模块和内置函数“mean”,但显然它只适用于数组。我不知道如何将循环的结果解析为数组(或者可能有不同的解决方案?任何帮助表示赞赏!

var a = @[100.0,102.0,101.0,114.0, 128.0, 130.0, 127.0]
var b = a [1..high(a)]&a[high(a)]


 for i in low(a)..high(a):


  echo i+1," period ", "= ", (b[i]/a[i])
4

1 回答 1

1

The important part is to make a new sequence with var c = newSeq[float]() and add values to it with c.add(value), as in the first block here:

var a = @[100.0, 102.0, 101.0, 114.0, 128.0, 130.0, 127.0]
var b = a[1..a.high] & a[a.high]

import math

block: # Iterative with math.mean
  var c = newSeq[float]()

  for i in a.low..a.high:
    c.add(b[i]/a[i])

  echo mean(c)

block: # Iterative without math.mean (most efficient)
  var myMean = 0.0

  for i in a.low..a.high:
    myMean += b[i]/a[i]

  myMean /= a.len.float
  echo myMean

import sequtils

block: # Functionally (not really nim-like)
  echo zip(a, b).map(proc(x): float = x.b/x.a).mean
于 2015-01-27T19:32:11.830 回答