簡體   English   中英

如何從用戶輸入獲取數組的每個元素,然后將其傳遞給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);
}

實驗室8

#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

問題是您要在inner_product()函數中從1進行迭代,並且應該從0進行迭代。

for( i=1; i<count; i++) {
/*     ^ this should be 0 */

同樣,不要特別使用全局變量,因為您可以正確使用其余部分,而是將數組作為參數傳遞給inner_product()函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM