C 有人能解释为什么这段代码给出运行时错误吗?
我找不到此程序的正确输出。它导致运行时错误C 有人能解释为什么这段代码给出运行时错误吗?,c,runtime-error,C,Runtime Error,我找不到此程序的正确输出。它导致运行时错误 #include <stdio.h> int main() { int c = 5, no = 10; do { no /= c; } while(c--); printf ("%d\n", no); return 0; } #包括 int main() { int c=5,no=10; 做{ no/=c; }而(c-); printf(“%d\n”,否); 返回0; } 它被零除
#include <stdio.h>
int main()
{
int c = 5, no = 10;
do {
no /= c;
} while(c--);
printf ("%d\n", no);
return 0;
}
#包括
int main()
{
int c=5,no=10;
做{
no/=c;
}而(c-);
printf(“%d\n”,否);
返回0;
}
它被零除。由于您在循环计数器c
中使用后减量,因此在上一次迭代中它将变为0
。既然您从@EugeneSh的答案中知道了运行时错误的原因,下面介绍了如何修复它
do {
no /= c;
} while(--c); // Use pre-increment instead of post-increment.
除以上所有答案外,我只想说最好在除法之前检查一个数字是否为零-
#include <stdio.h>
int main()
{
int c = 5, no = 10;
do {
if(c!=0){
no /= c;
}
} while(c--);
printf ("%d\n", no);
return 0;
}
#包括
int main()
{
int c=5,no=10;
做{
如果(c!=0){
no/=c;
}
}而(c-);
printf(“%d\n”,否);
返回0;
}
这将防止此类运行时错误
希望能有所帮助。非常感谢。因为
c
最终将变成0
,您将被零除。请注意,当c
为1
时,while(c--)
将为true,但c
将由于后减量而在循环内变为0
。