2015-02-24 44 views
-4

自己SUMM取代我不得不
我想有一個數字可以用C語言

1. create an array from N elements, which contains natural numbers 
2. And then I have to replace each number in array with its own summ. 

例如

23 -> 2 + 3 = 5; 
2 -> 2; 
845 -> 8 + 4 + 5 = 17 

所有這一切都必須用C來創建。任何人都可以幫我嗎?

+2

歡迎堆棧溢出!請參考[遊覽](http://stackoverflow.com/tour)並閱讀[如何提問](http://stackoverflow.com/help/how-to-ask)以瞭解我們對問題的期望。請注意,我們在這裏不提供_from-scratch_ coding服務。 :-) – 2015-02-24 07:38:47

+3

如果您嘗試一些事情,我們會幫助您,爲您編寫完整的代碼就是您想要的內容? – Vagish 2015-02-24 07:40:25

回答

-1

這裏的程序:

#include <stdio.h> 

int getSum(int value){ 
    int sum = 0; 
    int index = 0; 
    while (value > 0){ 
     sum += value % 10; 
     value = value/10; 
    } 
    return sum; 
} 

int main(int argc, char *argv[]) 
{ 
    int arr[] = { 23, 2, 845 }; 
    int i = 0; 
    int sizeArr = sizeof(arr)/sizeof(arr[0]); 
    for (i = 0; i < sizeArr; i++){ 
     arr[i] = getSum(arr[i]); 
     printf("%d\n", arr[i]); 
    } 
    return(0); 
} 
-2
#include <stdio.h> 

int main() 
{ 

    int a[5]={11,23,485,561,452}, i=0; 
    int tmp =i; 
    int total = 0; 

    for(i=0;i<5;i++) 
    { 
    tmp = a[i]; 
    while(tmp>0) 
    { 
     total = (tmp %10) + total; 
     tmp = tmp /10; 
    } 
    a[i] = total; 
    total =0; 
} 
// print array 
for(i=0;i<5;i++) 
{ 
    printf("%d = %d\n",i,a[i]); 
} 
    return 0; 

} 

// Output 
    0 = 2 
    1 = 5 
    2 = 17 
    3 = 12 
    4 = 11 
相關問題