2017-11-10 4 views
2

かなり基本的な手順でなければならないので、私は混乱させてしまう問題に直面しています。私はF#で単純なコンソールアプリケーションを構築する方法を学んでいますが、標準入力として整数をプログラムに渡す方法を理解することはできません。検討してください:標準入力で関数を初期化する

open System 

let square x = x * x 

[<EntryPoint>] 
let main (argv :string[]) = 
    printfn "The function will take an input and square it" 
    printfn "%d squared is %d" 12 (square 12) 
Console.ReadLine() |> ignore 
0 

どのように私はprintfnsquareに私はC言語で行うことができる方法値を渡すことができます:私は、整数、ないかなりの結果を得るためにlet x = Console.ReadLine()を適応しようとした

int main(){ 
    int i; 
    scanf("%d", &i); 
    printf("\nThe value of variable i is %d.\n", i); 
    return 0; 
} 

を。 documentation私は相談し、主に文字列の入力を検討します。私は、F#の基本を正しく理解するために重要なことが不足しているのではないかと心配しています。この意味で、どんな提案も高く評価されます。

+2

'int.Parseは()'あなたの友人 –

+0

おかげ@JohnPalmerで、私はそれに練習の少しを行います。次のプログラムは、あなたの基本的なアイデアを与える必要があります。 – Worice

答えて

4

ReadLine()は文字列を返します。 @ JohnPalmerが述べたように、intに解析する必要があります。

let rec input() = 
    printf "Input: " 
    match Core.int.TryParse (stdin.ReadLine()) with 
    | true, i -> i 
    | _ -> 
     printfn "Invalid input, try again" 
     input() 

let square x = x * x 

[<EntryPoint>] 
let main _ = 
    printfn "The function will take an input and square it" 
    let i = input() 
    printfn "%d squared is %d" i (square i) 
    0 
+0

この簡単な例をありがとうございました。 – Worice

関連する問題