如何从用户输入中获取数组的每个元素,然后将其传递给 C 中另一个文件中的函数

How to get each element of a array from user input then pass it to a function in another file in C

如何从用户输入中获取数组的每个元素,然后将其传递给另一个文件中的函数。我遇到了麻烦,需要帮助。这是我的代码。

main.c

#include <stdio.h>
#include "lab8.h"

int x[100];
int y[100];

int main(void) {  
    int count, i, product;

    printf("Enter the length of both arrays\n");
    scanf("%d", &count);

    printf("Enter the first array's elements\n");
    for(i=0; i<count; i++){
        scanf("%i", &x[i]);
    }
    printf("Element: %i\n", x[i]);
    printf("Enter the second array's elements\n");
    for(i=0; i<count; i++){
        scanf("%i", &y[i]);
    }   
    product = inner_product(x, y, count);
    printf("Inner product: %i\n", product);

    return(0);
}

lab8.c

#include <stdio.h>
#include "lab8.h"

int inner_product(int a[], int b[], int count) {
    int i;
    int result = 0;

    for( i=1; i<count; i++) {
        result = result + (a[i] * b[i]);
    }    
    return result;
}

输出似乎只是将两个数组输入的最后一个元素相乘。

Enter the length of both arrays
2
Enter the first array's elements
1
2
Element: 0
Enter the second array's elements
3
3
Inner product: 6

问题是您正在从 1 进行迭代,您应该在 inner_product() 函数

中从 0 进行迭代
for( i=1; i<count; i++) {
/*     ^ this should be 0 */

此外,不要专门使用全局变量,因为您已经正确地掌握了其余部分,您正在将数组作为参数传递给 inner_product() 函数。