use*_*781 2 haskell syntax-error
我必须写一个简单的程序告诉我,有多少解有二次方程.我写:
howManySolutions :: Float -> Float -> Float -> Int
howManySolutions a b c = if (b^2-(4*a*c)) > 0 then 2 else
if (b^2-(4*a*c)) == 0 then 1
else -1
Run Code Online (Sandbox Code Playgroud)
但在WinHugs中我收到语法错误:
unexpected ´;' possibly due to bad layout
Run Code Online (Sandbox Code Playgroud)
我可以在GHCi中打开我的程序,但它不会让我使用负数...我做错了什么?
我不确定winhugs问题,但我可以帮助你解决问题.
首先,有点缩进:
howManySolutions a b c = if (b^2-(4*a*c)) > 0
then 2
else
if (b^2-(4*a*c)) == 0
then 1
else -1
Run Code Online (Sandbox Code Playgroud)
现在,如果你尝试进入howManySolutions -1 2 3ghci,你会得到No instance for (Num (Float -> Float -> Float -> Int)) arising from a use of '-'.基本上它将' - '解释为应用于1 2和3而不是仅将其应用于'1'的函数.
您需要做的就是输入它howManySolutions (-1) 2 3.
现在,如果我可以给你一个提示,通常处理像这样的模式的方式是这样的:
howManySolutions a b c
| delta > 0 = 2
| delta == 0 = 1
| otherwise = -1
where delta = b^2-4*a*c
Run Code Online (Sandbox Code Playgroud)
'|' 符号(警卫)充当不同的'ifs',并且底部的'where'子句允许您定义delta一次以在警卫中重复使用多次.它更漂亮:D
| 归档时间: |
|
| 查看次数: |
1811 次 |
| 最近记录: |