在F#中查找最大值,最小值和平均值 [英] Find maximum, minimum and average in F#

查看:109
本文介绍了在F#中查找最大值,最小值和平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在F#中没有.NET的数组中找到最大值,最小值和平均值. 我使用了这段代码,但是它不起作用:

I want to find maximum, minimum and average in an array without .NET in F#. I used this code but it is not working:

let mutable max = 0
let arrX = [|9; 11; 3; 4; 5; 6; 7; 8|]

for i in 0 .. arrX.Length - 2 do
  if (arrX.[i]) < (arrX.[i+1]) then 
       max <- arrX.[i]
       printfn "%i" max

推荐答案

我已将代码固定为max

I fixed your code for max

let mutable max = 0
let arrX= [|9; 11; 3; 4; 5; 6; 7; 8|]

for i in 0 .. arrX.Length - 1 do
  if max < (arrX.[i]) then 
       max <- arrX.[i]
       printfn "%i" max

使用您的方法来查找最大值,最小值和平均值:

To find max, min and avg, using your approach:

let mutable max = System.Int32.MinValue
let mutable min = System.Int32.MaxValue
let mutable sum = 0
let arrX= [|9; 11; 3; 4; 5; 6; 7; 8|]

for i in 0 .. arrX.Length - 1 do
  if max < (arrX.[i]) then 
       max <- arrX.[i]
       printfn "max %i" max
  if min > (arrX.[i]) then 
       min <- arrX.[i]
       printfn "min %i" min
  sum <- sum + arrX.[i]
printfn "-> max is %i" max
printfn "-> min is %i" min
printfn "-> avg is %f" (float sum / float arrX.Length)

但是请注意,您可以执行以下操作:

But note you can do just:

let max = Seq.max arrX
let min = Seq.min arrX
let avg = Seq.averageBy float arrX

这篇关于在F#中查找最大值,最小值和平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆