我必须
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中创建。有谁可以帮助我?
答案 0 :(得分:-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);
}
答案 1 :(得分:-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