码迷,mamicode.com
首页 > 其他好文 > 详细

F# 学习笔记(流程控制)

时间:2015-07-05 18:27:59      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:

流程控制关键字

if:

    let mutable x = 17*17 - 15*15
    if x % 2 = 1 then x <- x - 1

while:

[<EntryPoint>]
let main argv = 
    let nr_fib n =
        let mutable a,b,i = 1I,1I,1
        while i < n do 
            let t = b
            b <- a+b
            a <- t
            i <- i+1
        a
    (nr_fib 10).ToString() |> printfn "%s"
    0 // 返回整数退出代码

for:

[<EntryPoint>]
let main argv = 
    for i=1 to 10 do
        i*i |>  printf "%i " 
    for i=10 downto 1 do
        i*i |>  printf "%i " 
    0 // 返回整数退出代码

for遍历:

[<EntryPoint>]
let main argv = 
    let s = "audfastaahe"
    for c in s do
        (int c) |> printf "%i " 
    0 // 返回整数退出代码

范围表达式,支持分段递增,或递减:

[<EntryPoint>]
let main argv = 
    for i in 1..10 do
        (i*i) |> printf "%i " 
    printfn ""
    for i in 1..2..10 do
        (i*i) |> printf "%i "
    printfn ""
    for i in 10..-3..0 do
        (i*i) |> printf "%i "
    0 // 返回整数退出代码

结合使用程序:

[<EntryPoint>]
let main argv = 
    System.Console.WriteLine "请输入步长"
    let s = System.Console.ReadLine()
    let step = System.Int32.Parse s
    let a, b = 
        if step > 0 then 1,100
        else 100, 1
    for i in a..step..b do
        printf "%i " (i*i)
    0 // 返回整数退出代码

异常处理,使用try,with 语句

open System
[<EntryPoint>]
let main argv = 
    try
        let x = Int32.Parse(Console.ReadLine())
        printfn "x=%i" x
        let y = 1200 / (x-2) / (3-x) / x
        printfn "y=%i" y 
    with
        | :? FormatException -> printfn "输入格式不正确"
        | :? DivideByZeroException -> printfn "除数不能为0"
        | _ -> printfn "发生程序异常"
    printfn "程序继续运行"
    0 // 返回整数退出代码

异常处理,try,finally语句:

open System
[<EntryPoint>]
let main argv = 
    try
        let n = Int32.Parse(Console.ReadLine())
        printfn "请输入一组数,中间以逗号分隔:"
        let mutable ss = Console.ReadLine().Split(,)
        let mutable s = 0.0
        try
            for i = 0 to n do
            s <- s + Double.Parse(ss.[i])
        finally
            ss <- null
            printfn "s=%.2f" s
    with
        | e -> printfn "程序处理过程中发生异常"
    0 // 返回整数退出代码

手动抛出异常,有3种模式,raise是可以指定异常类型的手动抛出,第二种是参数异常,第三种则引发基础异常:

    raise(ArgumentException("参数值不能为0,2,3"))
    invalidArg "参数值不能为0,2,3" "x"
    failwith "参数值不能为0,2,3"

素因数分解,例子:

open System
[<EntryPoint>]
let main argv = 
    let dec x = 
        printf "%i = " x
        let mutable x1 = x
        let mutable i = 2
        while x1 > 1 do 
            if x1 % i = 0 then
                printf "%i * " i
                x1 <- x1 / i
            else
            i <- i + 1
        printfn "%i" x1
    printf "请输入一个整数:"
    try
        let x = Int32.Parse(Console.ReadLine())
        dec x 
    with
        |e -> printfn "数值格式不正确"
    0 // 返回整数退出代码

 

F# 学习笔记(流程控制)

标签:

原文地址:http://www.cnblogs.com/qugangf/p/4622739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!