以下代码使我感到惊讶:
julia> for person in 1:12
println("person is $(lpad(2, person))")
end
person is 2
person is 2
person is 2
person is 2
person is 2
person is 2
person is 2
person is 2
person is 2
person is 2
person is 2
person is 2
直到我意识到我以相反的顺序输入lpad
函数的参数之前,这似乎是完全神秘的。修复它:
julia> for person in 1:12
println("person is $(lpad(person, 2))")
end
person is 1
person is 2
person is 3
person is 4
person is 5
person is 6
person is 7
person is 8
person is 9
person is 10
person is 11
person is 12
但是,肯定发生了一些我无法理解的lpad
和意外的输出。
下面是docs中lpad
函数的签名:
lpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') -> String
有什么建议吗?
答案 0 :(得分:1)
由于某种原因,您的循环计数器称为“人”。因此它从1循环到12。
从函数docs中,第二个参数确定 打印的第一个参数:
lpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') -> String
Stringify s and pad the resulting string on the left with p to make
it n characters (code points) long. If s is already n characters long,
an equal string is returned. Pad with spaces by default.
所以您的循环计数器是个人,这也是空格数 在第一个版本的输出的每一行的'2'之前打印。