I'm trying to solve this challenge在 Hackerrank 上。
我遇到了无法继续的问题,但我看不出哪里出了问题 - 我希望这里有人能提供帮助。
我目前的解决方案如下:
int main() {
int n,k,p,count,total;
int t[n];
scanf("%d %d",&n,&k);
for(int i = 0; i < n; i++){
scanf("%d",&t[i]);
}
p = 1;
total=0;
for(int x = 0; x < n; x++){
for(int j = 1; j <= t[x]; j++, count++){
if(count>k){
count = 1;
p++;
}
if(j==p){
total++;
}
//printf("j: %d p: %d\tcount: %d\n",j,p,count);
}
p++;
count=1;
}
printf("%d",total);
return 0;
}
我注释掉的 printf 改变了我的最终输出。 例如,输入:
10 5
3 8 15 11 14 1 9 2 24 31
我应该得到 8 的答案。如果我取消注释 printf()
函数,那么我可以看到当前的问题编号和页码,看看它是否“特殊”。
如果我不评论它,我最终的输出是 8,这就是我想要的。但我也不希望打印出所有迭代。
我遇到的问题是,当我删除该行或将其注释掉时,输出变为 5,而不是 8。
是什么导致了这种变化?
最佳答案
在您的代码中,在定义 int t[n];
时,您正在使用未初始化的 n
。那 , 调用 undefined behavior .
详细来说,n
是一个自动局部变量,没有显式初始化,因此该变量的内容是不确定的。尝试使用不确定的值会导致 UB。
引用 C11
,第 6.7.9 章
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [...]
并且,附件 §J.2,未定义的行为,
The value of an object with automatic storage duration is used while it is indeterminate
您需要移动 int t[n];
的定义在您成功扫描了用户的值之后。检查scanf()
的返回值,确保成功。
关于c - printf 改变了我的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39268568/