【问题标题】:End program after number of inputs输入次数后结束程序
【发布时间】:2021-04-18 14:53:02
【问题描述】:

我的程序做什么?从用户那里获取输入,它需要在 0-99 之间。 当用户猜出数字“猜”为 45 或尝试 10 次后,程序结束。 问题是我无法弄清楚这个游戏的第二部分。

guess = 45

game = do
putStrLn ("Give a number between 0 and 99")
a <- getLine
let x = read a
if x == guess then print ("You got it!") else game

【问题讨论】:

  • 创建一个辅助函数,在其中使用参数作为猜测次数,并使用递减的值递归调用它。

标签: haskell functional-programming increment


【解决方案1】:

您可以创建一个辅助函数,在其中使用带有猜测次数的参数。每次进行递归调用时,递减猜测次数,如果变量小于或等于 0,我们可以停止递归:

guess :: Int
guess = 45

tries :: Int
tries = 10

main :: IO ()
main = game tries

game :: Int -> IO ()
game n
  | n <= 0 = putStrLn "end of the game"
  | otherwise = do
      putStrLn "Give a number between 0 and 99"
      a <- readLn
      if a == guess then putStrLn "You got it!" else game (n-1)

【讨论】:

  • 我遇到了两个错误 - 第一个是“main 的多个声明”,第二个是“变量 a 不在范围内:
  • @dronikk:你的程序定义了另一个main
  • 它实际上是我在 .hs 文件中得到的唯一程序
  • @dronikk:但您在进行修改之前已经运行了另一个程序,因此您在某处定义了 main
  • 我什至尝试更改它的名称,但它仍然是一样的。这就是错误的样子:i.imgur.com/zTPFZGP.png
【解决方案2】:

谢谢威廉!不得不重新排列代码中的一些东西,但你给了我这个想法。这就是现在的样子:

guess = 45
tries = 10

main = zad5 tries

zad5 y = do
putStrLn ("Give a number between 0 and 99")
a <- getLine
let x = read a
if y==1 || x == guess then print ("end of the game") else zad5 (y-1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2016-07-15
    相关资源
    最近更新 更多