#include <stdio.h>
main()
{
int num[9], i = 0, count = 0;
while (i<10)
{
scanf("%d", &num[i]);
if (num[i] % 2 == 0)
{
count++;
}
i++;
}
printf("we have %d double numbers\n", count);
}
运行时检查失败#2 - 变量周围的堆栈已损坏
我该怎么办?
答案 0 :(得分:4)
您的while循环会将i
的所有值从0到9(包括0和9),但尝试访问num[9]
会使您超出范围。您需要减少while循环范围:
while (i<9) {
...
}
此外,你真的应该给你的main()
函数一个返回类型,因为现代编译器不能容忍它丢失:
int main()
{
...
return 0;
}
答案 1 :(得分:2)
可用于访问具有N个元素的数组的索引的有效范围是[0, N - 1]
或者是相同的[0,N]。
因此while语句中的条件
while (i<10)
必须像
一样重写while (i < 9)
错误的原因是在整个程序中使用“幻数”。 尝试使用命名常量而不是幻数,在这种情况下,很容易理解在代码的哪个部分使用了什么幻数。
程序看起来像
#include <stdio.h>
#define N 9
int main( void )
{
int num[N];
unsigned int count = 0;
unsigned int i = 0;
while ( i < N )
{
scanf( "%d", &num[i] );
if ( num[i] % 2 == 0 ) ++count;
i++;
}
printf( "we have %u double numbers\n", count);
}
而不是while循环,最好使用for循环,因为变量i
不在循环外使用。
例如
#include <stdio.h>
#define N 9
int main( void )
{
int num[N];
unsigned int count = 0;
for ( unsigned int i = 0; i < N; i++ )
{
scanf( "%d", &num[i] );
if ( num[i] % 2 == 0 ) ++count;
}
printf( "we have %u double numbers\n", count);
}
声明数组索引的更正确的方法是使用类型size_t
。
实际上该程序中没有使用该数组。您可以在不使用数组的情况下计算输入的值。
考虑到根据C标准,不带参数的函数main
应声明为
int main( void )