求命令行传入整数参数的和

main.c:

#include <stdio.h>
#include <stdlib.h>

extern int sum(int a[],int num);
int main(int argc, char *argv[])
{
    int result = 0;
    int num[argc];
    int i = 0;
    for(i=0; i < argc ;i++) 
    {
        num[i] = 0;
    }
    
    for(i=0; i < argc ;i++) 
    {
        num[i] = atoi(argv[i]);
        result = sum(num,argc);
    }
    printf("%d\n",result);
    return 0;
}

sum.c

int sum(int a[],int num)
{
    int i = 0;
    int sum = 0;
    for ( i = 0; i < num; i++)
    {
        sum += a[i];
    }
    return sum;
}

运行截图:

posted @ 2021-11-15 11:33  Bzrael  阅读(51)  评论(0编辑  收藏  举报