所以我刚刚创建了一个程序,要求输入一个 n ,并显示 n 斐波纳契数列的术语:
import Control.Monad (forever)
main = forever $ do
putStrLn ""
putStr "Which Fibonacci sequence number do you need? "
number <- readLn :: IO Int
putStrLn $ "The Fibonacci number you wanted is " ++ (show $ fib number) ++ "."
putStrLn ""
where fib :: Int -> Integer
fib number = fibs !! number
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
当我在GHCi或runhaskell中运行程序时,它执行正常;也就是说,要求我输入一个数字,允许我在同一行输入它并在另一行返回一个数字:
Gallifreian@Gallifrey:~/Haskell$ ghci
GHCi, version 7.10.3: http://www.haskell.org/ghc/ :? for help
Prelude> :l Fib.hs
[1 of 1] Compiling Main ( Fib.hs, interpreted )
Ok, modules loaded: Main.
*Main> main
Which Fibonacci sequence number do you need? 4
The Fibonacci number you wanted is 3.
但是,当我运行已编译的程序时,它会返回:
Gallifreian@Gallifrey:~/Haskell$ ./Fib
4
Which Fibonacci sequence number do you need? The Fibonacci number you wanted is 3.
予。即等待我输入一个数字,然后在一行上返回所有提示。 我做错了什么?有办法解决这个问题吗?
答案 0 :(得分:1)
看起来stdout有行缓冲,这意味着对putStr的调用只将输出存储在缓冲区中,直到调用putStrLn才会输出。您可以通过使用putStrLn来提示输出或在stdout上禁用缓冲来修复输出。