/* 我想查看 short int 的最大值。我只想使用循环查看它。所以我创建了一个无限循环。问题是我想停止循环以查看每 1000 个值后的值.但是它只有在循环到1000时才停止,因为我已经给它停止使用if条件,然后它永远不会停止。我该怎么做才能在每1000个值后停止。下面给出程序*/
#include<stdio.h>
#include<conio.h>
void main()
{
//Short int is declared intentionally
short int d=0;
char i;
//Infinite loop is created intentionally
for(d=0; ;d++)
{
//printing value
printf("\n%d",d);
//stopping a loop when value reaches 1000
if(d==1000)
{
//continuing after pressing a character after 1000
printf("\n press i to continue");
scanf("%d",&i);
continue;
}
}
//see the output
getch();
}
最佳答案
您使用错误的格式说明符来扫描 char
值(value)。它调用 undefined behavior .你应该改变
scanf("%d",&i);
到
scanf(" %c",&i);
也就是说,要在 每 1000 次迭代时停止,您需要更改 if(d==1000)
至 if( (d % 1000) == 0)
.
FWW,
-
void main()
应该是int main(void)
,至少要符合标准。 - 有符号整数类型溢出又是 UB。你不应该依赖它。使用
<limits.h>
检查范围(如果有)。
关于c - 如何在每 1000 个值后停止无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35633704/