gpt4 book ai didi

c - fflush(stdin) 的工作如何改变下面代码中的输出?

转载 作者:行者123 更新时间:2023-11-30 18:24:38 26 4
gpt4 key购买 nike

#include <stdio.h>
int main()
{
int test_no ,count=1,i,n,j;
scanf("%d",&test_no);
fflush(stdin);
int arr1[test_no];
for(i=0;i<test_no;i++)
{
scanf("%d",&n);
printf("\n");
int arr[n];
for(j=0;j<n;j++)
{
fflush(stdin);
scanf("%d",&arr[i]);
}
for(j=1;j<=n-1;j++)
{
if(arr[j-1]>arr[j])
{
count++;
}
}
if(n==1)
{
arr1[i]=1;
}
else
{
arr1[i]=count;
}
count=1;
}
for(i=0;i<test_no;i++)
{
printf("%d\n",arr1[i]) ;
}
return 0;
}

这个解决方案是针对这个problem .

我没有得到第三种情况所需的输出,它给我输出为 3 或 4,具体取决于我是否在 scanf("%d", arr[i]) 或在 scanf("%d",arr[i]) 之后,请告诉此代码的问题。

最佳答案

某种神奇的方式。

首先,fflush(stdin); 调用undefined behavior不要使用它。

引用 C11,第 §7.21.5.2 章,fflush 函数(强调我的)

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

也就是说,

for(j=0;j<n;j++)
{
fflush(stdin);
scanf("%d",&arr[i]);
}

对我来说看起来很错误,arr[i] 不能保证在范围内。应该是这样

scanf("%d",&arr[j]);

关于c - fflush(stdin) 的工作如何改变下面代码中的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38325884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com