我一直在和Julia一起解决哈佛CS50的问题集。这个脚本是我[多数选举]的解决方案。1
println("How many contenders do we have?")
const max_candidates = parse(Int, readline()) # a maximal number of candidates
# Let us define a composite type for the candidates in our elections
mutable struct Candidate
name::String
votes::Int64
end
function vote(name)
for i in 1:max_candidates
if candidates[i].name == name
candidates[i].votes = candidates[i].votes + 1
end
end
end
function print_winner()
max_votes = 0
for i in 1:max_candidates
if candidates[i].votes > max_votes
max_votes = candidates[i].votes
end
end
for i in 1:max_candidates
if candidates[i].votes == max_votes
candidates[i].name
end
end
end
candidates = Vector{Candidate}(undef, max_candidates)
for i in 1:max_candidates -1
println("Name of the candidate: ?")
name = readline()
votes = 0
candidates[i] = Candidate(name, votes)
println("Thank you, let us move to the next candidate.")
end
#The last candidate i registered outside of the loop because I do no want
#the line println("Thank you, let us move to the next candidate.") to be executed after them.
println("Name of the last candidate: ?")
name = readline()
votes = 0
candidates[max_candidates] = Candidate(name, votes)
println("How many voters do we have?")
voter_count = parse(Int, readline())
for i in 1:voter_count
println("Who are you voting for?")
name = readline()
vote(name)
end
winner = print_winner()
println(winner)
当我运行此脚本时,出现以下错误
ERROR: LoadError: ArgumentError: `nothing` should not be printed; use `show`, `repr`, or custom output instead.
Stacktrace:
[1] print(::Base.TTY, ::Nothing) at ./show.jl:566
[2] print(::Base.TTY, ::Nothing, ::Char) at ./strings/io.jl:42
[3] println(::Base.TTY, ::Nothing) at ./strings/io.jl:69
[4] println(::Nothing) at ./coreio.jl:4
[5] top-level scope at none:0
[6] include at ./boot.jl:317 [inlined]
[7] include_relative(::Module, ::String) at ./loading.jl:1044
[8] include(::Module, ::String) at ./sysimg.jl:29
[9] exec_options(::Base.JLOptions) at ./client.jl:266
[10] _start() at ./client.jl:425
in expression starting at /home/jerzy/C.../plurality.jl:65
错误消息中的表达式称为"表达式从/home/jerzy/C 开始.../plurality.jl:65"是脚本的姓氏。 我不明白这是什么nothing
? 尽管如此,按照错误消息的建议,我修改了代码的最后一行,将其从:
println(winner)
自
show(winner)
并得到以下输出:
无
我在这里和那里做了一些研究,但作为一个新手,我不明白为什么我不能从我的函数print_winner返回一个值。从我读到的内容来看,返回声明不是强制性的。
在print_winner的定义中,当我替换
candidates[i].name
跟
println(candidates[i].name)
然后当最后一行是
winner = print_winner()
然后我终于能够得到获胜者的名字。但这不是我想要的方式。我想返回一个值并将其分配给一个变量,然后用这个变量做一些事情。我可以在PHP或Racket中做到这一点,为什么我不能在Julia中做到这一点?
函数print_winner
不返回任何内容,在这种情况下,对象nothing
实际上被返回。所以winner
得到值nothing
(来自winner = print_winner()
(,println(winner)
等效于println(nothing)
,这会导致错误。
我想返回一个值并将其分配给一个变量
然后这样做:从print_winner
返回一个值。Julia 无法知道您希望此函数返回什么,因此您必须明确说明它。默认情况下,Julia 返回函数表达式的值,在本例中是最后一个表达式的结果,此处为for
循环。for
循环的表达式值在 Julia 中nothing
。