2015-05-16 28 views
0

我正在嘗試編寫一個函數來檢查一個特定的數字,如果它找到了這個數字,它就將它添加到總數中。函數的難點 - C

#include <stdio.h> 

void unitSum(int input[], int output, int unit) 
{  
    for (int n = 0; n < 5; n++) 
    { 
     if(input[n] == unit) 
     output = output + unit; 
    } 
} 

int main (void) 
{ 
    int array[5]; 
    int total = 0; 

    for(int a = 0; a < 5; a++) 
    { 
    scanf("%d", &array[a]); 
    } 

    unitSum(array, total, 1); 

/*for (int n = 0; n < 5; n++) 
    { 
     if(array[n] == 1) 
     total = total + 1; 
    }*/ 

    printf("%d", total); 
} 

如果我輸入「1 1 1 2 2」運行這個程序,我得到的0輸出然而,如果我取消了在底部循環,並註釋掉函數調用。輸出變成3(我想要的)。

我是否缺少一些簡單的東西?

+1

的問題是,你的函數'unitSum'不改變'output'值。你應該在'main'中調用'unitSum(array,&total,1)'而不是'unitSum(array,total,1)'。 –

+0

所以我如果我想編輯函數外的變量值,我必須在變量名之前加一個&符號?編輯 - 它沒有修復它 – maffu

+0

是的肯定。只需添加&符號不會解決問題。你必須進一步瞭解'指針'來看它是如何工作的。 –

回答

1

只是改變你的調用函數行unitSum(array,total,1);

to total = unitSum(array,total,1);在你的函數unitSum改變

返回類型爲int和關閉的loop.It將

解決後返回的輸出。

int unitSum(int input[], int output, int unit) 
{  
    for (int n = 0; n < 5; n++) 
    { 
     if(input[n] == unit) 
     output = output + unit; 
    } 
    return output; 
} 

快樂編碼。

5
C

,參數由過去了,沒有參考,這意味着你的函數使得複製您的變量output和處理只與拷貝,這樣就不會改變原來的。所以如果你想要一個函數改變他的一個參數而不是在本地,你必須通過一個指針它。
在你的代碼,這將解決:

// int *output is the pointer to an int variable 
void unitSum(int input[], int *output, int unit) 
{  
    for (int n = 0; n < 5; n++) { 
     if(input[n] == unit) 
      // here you change the value of the variable that is 
      // located in this address in memory 
      (*output) = (*output) + unit; 
    } 
} 

// ... 

// &total is the pointer to variable total 
unitSum(array, &total, 1);