对于著名的问题。
有 100 个人围成一圈,编号从 1 到 100。第一个人拿着剑,顺时针杀死站在他旁边的人,即 1 杀 2,以此类推。最后存活下来的数字是哪一个?最后一个数字是哪个?
在下面的 C 代码中解决这个问题。
void main(){
int i=0, j; //i has the sword, j gets killed.
int a[N]={0}; //0=not killed
while(1){
if(i != N-1) j = i + 1;
else j = 0;
while(a[j])
if((j + 1) == N) j = 0; //loop back to 0
else j++; //skip over the killed people
if(i==j){ //if i is the only one left, stop
printf("\n\n\n%d is left!", i+1);
return;
}
a[j] = 1; //kill j
printf(" %d kills %d.", i+1, j+1);
if(j != N-1) i = j + 1;
else i=0;
while(a[i])
if((i + 1) == N) i = 0;
else i++;
}
}
请告诉我 int a[N]={0};
的含义//0=没有在第 1 行被杀死。 6 谢谢。
最佳答案
在您的代码中,
int a[N]={0};
正在将数组a
的所有成员初始化为0。
根据 C11
标准,第 §6.7.9 章,初始化,(强调我的)
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
并且,对于静态存储类型int
的初始化器值,它是算术类型,
[...] if it has arithmetic type, it is initialized to (positive or unsigned) zero;
和a
是一个int
类型的数组,因此它的所有成员都被初始化为0
作为值。 a[0]
将显式初始化为 0
(已提供),其余部分将获得隐式初始化。
FWIW,N
必须是编译时常量值,例如
#define N 50 //or any value
为了让它发挥作用。
关于C编程,int a[N]={0};这句话的含义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37237592/