在不初始化的情况下声明变量将具有垃圾值,因此在此程序中我使用的是union:
>>> my_list = [a[0] for a in x]
# since it is a `list`, you can take it's length
>>> len(my_list)
3
只要我们没有初始化它就可以在打印时产生垃圾值。
但请看这个程序:
union un
{
int value;
char c;
};
int main()
{
un x;
x.c = 'A';
cout << x.value << endl; // garbage: ok
}
那么上面两个程序之间有什么区别?为什么第二个程序union un
{
int value;
char c;
}r;
int main()
{
r.c = 'A';
cout << r.value << endl; // 65! as we know the ASCII value of character 'A' is 65
}
得到value
的值?
答案 0 :(得分:2)
您的text = "4443466664"
# Define a variable here that represents the slice size to use
slice_size = 5
# Cut this into groups of 5 characters, convert each chunk by remapping
# the values to integers, then save it all into one variable.
halves = text.chars.each_slice(slice_size).map { |a| a.map(&:to_i) }
# The result looks like this:
# => [[4, 4, 4, 3, 4], [6, 6, 6, 6, 4]]
# Count all pairs that add up to more than 9 using count with a block
# that defines when to count them. Note the use of ... which goes up to
# but does not include the upper bound.
count = (0...slice_size).count do |i|
halves[0][i] + halves[1][i] > 9
end
# => 3
是一个全局变量。并将这些初始化为零。 r
的第一个字节是value
,其他字节是零。
相比之下,c
是一个局部变量,并且它们没有被初始化。 x
的第一个字节也是value
,但其他字节就像随机或垃圾一样,就像你所说的那样。