gpt4 book ai didi

c# - 有什么类似于 F# 中的 Switch Case 命令吗?

转载 作者:行者123 更新时间:2023-12-04 07:53:33 26 4
gpt4 key购买 nike

我是第一次练习 F# 编程,我想知道该语言中是否有一个命令可以模拟 C# 中的 Switch/Case 命令?我想确保优化程序,以便不必每次都重新设置它们以尝试程序的不同路线 (例如,创建三种面积计算器,并且必须重新设置以尝试每一种。)
编辑:我完全忘记了以代码为例。
这就是我想尝试和编辑的。

```module AreaCalculator =
printfn "------------------------------"
printfn "Enter 1 to find a rectangle's area."
printfn "Enter 2 to find a circle's area."
printfn "Enter 3 to find a triangle's area."
printfn "Enter here: "
let stringInput = System.Console.ReadLine()

if stringInput = "1" then
printfn "What is the rectangle's length: "
let rlString = System.Console.ReadLine()
printfn "What is the rectangle's width: "
let rwString = System.Console.ReadLine()

let rlInt = rlString |> int
let rwInt = rwString |> int
let rectArea = rlInt * rwInt

printfn "The area of the rectangle is: %i" rectArea
elif stringInput = "2" then
let PI = 3.14156
printfn "What is the circle's radius: "
let radiusString = System.Console.ReadLine()
let radiusInt = radiusString |> float
let cirlceArea = (radiusInt * radiusInt) * PI

printfn "The area of the circle is : %f" cirlceArea


elif stringInput = "3" then
printfn "What is the triangle's base: "
let baseString = System.Console.ReadLine()
printfn "What is the triangle's height: "
let heightString = System.Console.ReadLine()

let baseInt = baseString |> int
let heightInt = heightString |> int
let triArea = (heightInt * baseInt)/2

printfn "The area of the triangle is: %i" triArea

else
printfn "Please try again"
它按原样工作得很好,但我想看看我是否可以重新设计程序,这样就不必在每次你想计算不同形状的面积时都重新设置它。我试过制作 字符串输入 一个可变变量,正如我在演示文稿中看到的那样,但它只会导致如下错误:
/home/runner/F-Practice-1/main.fs(59,5):错误 FS0588:此“让”之后的 block 未完成。每个代码块都是一个表达式,并且必须有一个结果。 'let' 不能是 block 中的最后一个代码元素。考虑给这个 block 一个明确的结果。
我能做些什么来解决这个问题?

最佳答案

F# 中的等效结构称为 match :

let stringInput = System.Console.ReadLine()
match stringInput with
| "1" ->
printfn "What is the rectangle's length: "
// ...
| "2" ->
printfn "What is the circle's radius: "
// ...
| "3" ->
printfn "What is the triangle's base: "
// ...
| _ ->
printfn "Please try again"
更多详情 here .

关于c# - 有什么类似于 F# 中的 Switch Case 命令吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66822086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com