开发者

very simple loop in F#

开发者 https://www.devze.com 2022-12-18 18:57 出处:网络
I tried this in both FSI and VS2010.Both gives the same output.开发者_运维技巧 for i= 8 to 10 do

I tried this in both FSI and VS2010.Both gives the same output.开发者_运维技巧

for i= 8 to 10 do
    for j=7 to 10 do
    let product=i*j
    printfn "%d * %o = %x" i j product

and the output is:

8*7=38
8*10=40
8*11=48
8*12=50
9*7=3f
9*10=48
9*11=51
9*12=5a
10*7=46
10*10=50
10*11=5a
10*12=64
val it : unit = ()

Am i missing something here?

I try to learn programming (with F# because I loved it) with online tutorials.


The output seems correct to me, since you are formatting the output of i, j and product in decimal (%d), octal (%o) and hex (%x), respectively.

The numbers 7, 8, 9 and 10 are being formatted as 7, 10, 11, and 12 because that is their octal representation. Change them all to %d or %i to fix the problem.


Yes. You're missing something. 10(decimal) * 10 (octal) = 50 (hex). %d means decimal, %o means octal, and %x means hexidecimal. If you don't know what they are, google them.

The following are all the same statement.

In decimal:

10 * 8 = 80.

in octal:

12 * 10 = 120

in hex:

a * 8 = 50.

Please look closely at something before you copy it.


Guess it's about the formatting string of printfn. Just try %i.

for i = 8 to 10 do
    for j = 7 to 10 do
        let product=i*j
        printfn "%i * %i = %i" i j product


Note that the docs on printf format specifiers are here

http://msdn.microsoft.com/en-us/library/ee370560(VS.100).aspx

(though as of today, the formatting of the document is a little messed up, making it hard to read)

0

精彩评论

暂无评论...
验证码 换一张
取 消