Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Types 朱莉娅型问题_Types_Integer_Julia - Fatal编程技术网

Types 朱莉娅型问题

Types 朱莉娅型问题,types,integer,julia,Types,Integer,Julia,1为什么当我在函数中定义变量及其类型时,一切都很好,但当它是全局变量时,我会出错? 例如: 2为什么在执行一些简单操作时,变量类型会发生变化?示例: julia> function main() n::Int8 = 5 c = collect(1:n) println(c) println(typeof(c)) end main (generic function with 1 metho

1为什么当我在函数中定义变量及其类型时,一切都很好,但当它是全局变量时,我会出错? 例如:

2为什么在执行一些简单操作时,变量类型会发生变化?示例:

julia> function main()
           n::Int8 = 5
           c = collect(1:n)
           println(c)
           println(typeof(c))
       end
main (generic function with 1 method)

julia> main()
[1,2,3,4,5]
Array{Int64,1}


julia> n = zero(Int8)
0
julia> typeof(ans)
Int8
julia> n += 5
5
julia> typeof(ans)
Int64
3如何维护变量初始类型?

目前(Julia 0.4),Julia手册中的问题1和2由以下人员回答:

目前,类型声明不能在全局范围内使用,例如在REPL中,因为Julia还没有常量类型全局变量


正如在评论中所讨论的,在
n+=5
中有几个选项用于#3.

,即
n=n+5
5
是一个Int64。尝试
n+=Int8(5)
。否则,在将Int64添加到Int8时,获取Int64是合理的(请在Julia书中查找“升级”)。类似地,尝试
collect(Int8(1):Int8(5))
。断言
n::Int8
在以后分配值(
=3
)时不是多余的吗?另外,我认为
Int
会根据Julia运行的硬件自动转换为适当的类型,这就是
collect(1:n)
生成
Int64
数组的原因。请参见,在本例中,您也可以使用该函数:
c=collect(一(n):n)::Vector{Int8}
julia> function main()
           n::Int8 = 5
           c = collect(1:n)
           println(c)
           println(typeof(c))
       end
main (generic function with 1 method)

julia> main()
[1,2,3,4,5]
Array{Int64,1}


julia> n = zero(Int8)
0
julia> typeof(ans)
Int8
julia> n += 5
5
julia> typeof(ans)
Int64