我知道当程序消耗大量内存或在某处被0除时会发生运行时错误。 这是打印所有数字直到用户输入 42 的代码。(不打印 42)。
#include<stdio.h>
int main()
{
int n;
while(1)
{
scanf("%d",&n);
if(n==42)
break;
else
printf("%d",n);
}
}
请告诉我为什么在如此简单的代码中会出现运行时错误?
最佳答案
您的 main 函数应该返回一个 int,但您没有:这就是您收到运行时错误的原因。这是正确的代码:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 0;
while(1) {
scanf("%d",&n);
if(n == 42)
break;
else
printf("%d",n);
}
return EXIT_SUCCESS;
}
如果您不想包含 stdlib.h
,您还可以更改 return 0;
中的 return EXIT_SUCCESS;
,但这里是 why it's better .
您还应该考虑使用除 CodeChef 之外的其他 IDE。 CodeBlocks 或 VisualStudio 更好、更明确,带有错误和警告。在使用之前,您应该将 int n
设置为 0。
关于c - 为什么我会收到运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44083881/