This question has already been answered:

It is necessary to write each digit of a number into an array, and then add them up.

int n = 87654321; int size = IntCount(n);//к-во цифр в числе int array[size],i; // да, VLA лучше не использовать но так проще int stepen = size-1, // степень в какую возносим, самый старший разряд- [0] summa=0; for(i=0;i<size;i++) { array[i] = n/(int)pow(10,stepen)%10; //получаем каждую цифру и в массив summa=summa + array[i]; stepen--; // уменьшаем степень } printf("Сумма = %d",summa); 

As a result, the addition gives some nonsense, although the numbers in the array are correct. Perhaps the problem is in the modifier, but I do not understand why.

Reported as a duplicate by members of Mike , Visman , aleksandr barakin , αλεχολυτ , cheops 19 Oct '16 at 5:30 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • @ Hardc0re You did not receive an answer to your question why your code does not work. :) - Vlad from Moscow
  • @ Hardc0re Moreover, your problem is not reproduced, so you should show a minimally verifiable code showing the problem. - Vlad from Moscow

1 answer 1

To obtain a discharge, you must use the operation of obtaining the residue when divided by 10

 int n = 87654321; int size = IntCount(n);//к-во цифр в числе int array[size]; int summa = 0; for(int i = 0; i < size; i++) { array[i] = n % 10;//получаем последний разряд n /= 10; // убираем последний разряд summa += array[i]; } printf("Сумма = %d",summa); 
  • So what is the error in the source code of the question? - Vlad from Moscow
  • @VladfromMoscow probably here (int)pow(10,stepen) . It is rounded down, but you need to the nearest integer. Then from 9.9999999999 we get not 9, but, as expected, 10 - Anton Shchyrov
  • 8 This is a wrong conclusion, since the author of the question states that the numbers in the array are entered correctly, and I myself could not reproduce the problem for a given number. - Vlad from Moscow
  • @VladfromMoscow I don’t believe the statements for a long time, but I believe the code. You can see for yourself that if all the values ​​in the array are correct, then the sum cannot be mistaken. Hence, the error, all the same, in filling the array. This place is one of the candidates for error. The second candidate here is IntCount(n) - Anton Shchyrov
  • Therefore, your answer is not the answer to the question. You did not find out the cause of the error. It was necessary to require the author to show a minimal verifiable example demonstrating the problem. And so you just offered another solution, but the question remained unanswered. - Vlad from Moscow