c - 在 C 中使用大小为 10 的一维数组添加偶数

标签 c arrays loops for-loop undefined-behavior

计算一维所有偶数元素之和的程序 大小为 10 的数组。

#include<stdio.h>
void main(){
    int i,count=0;
    int a[10]; //one dimensional array with size 10
    for(i=0;i<=11;i++){
        a[i]=i; //assigning values to array
        if(i%2==0){
            count=count+a[i]; //add even numbers
        }
    }
    printf("%d",count); //output
}

我预计输出为 30,但实际输出为 20。

最佳答案

这个循环

for(i=0;i<=11;i++){

调用未定义的行为,因为在循环内尝试访问数组外部的内存。

如果数组有 N 个元素,则索引的有效范围为 [0, N)。所以重写循环就像

for(i=0;i < 10;i++){

错误的原因是使用了魔数(Magic Number)。使用命名常量而不是魔数(Magic Number)。例如

#include <stdio.h>

int main(void) 
{
    enum { N = 10 };
    int count = 0;
    int a[N];

    for ( int i = 0; i < N; i++ )
    {
        a[i] = i;

        if ( i % 2 == 0 )
        {
            count += a[i];
        }
    }

    printf( "%d\n", count ); 

    return 0;
}

注意,根据C标准,不带参数的函数main应该这样声明

int main( void )

关于c - 在 C 中使用大小为 10 的一维数组添加偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58432521/

相关文章:

c 多个文件描述符

java - 我需要知道如何在 java 中循环 .wav 文件 n 次

c - cuda中的共享内存

c - 对适当色带的电阻(欧姆)

c - 存储压缩集的最佳方式

c# - C#中的正则表达式解析为双数组

php - 内爆内部数组值

php - Twig - 打印没有空值的数组

javascript - 在元素名称发生变化的循环中解析 json

c - 释放子串而不在c中做双重释放