c - printf 改变了我的输出

标签 c arrays loops printf variable-length-array

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/

相关文章:

java - 寻找 3x3 矩阵的余因子和行列式 (java)

java - "How can I request an if-else input after a switch statement?"

c# - 如何存储 Switch 语句中的 Cases 列表?

c - 我是否使用循环来迭代小尺寸数组(例如 2 或 3)?

c - 尝试在 c 排序结构中实现快速排序

c - C 中 extern 关键字的行为

c# - 在单元测试中使用 StringBuilder 进行 PInvoking

Javascript 数组 100000 x 100000 - 杀死我的浏览器

C# 处理空格

c - C 中带有 char 条件的 if 语句