Другие языки программирования и технологии

Помогите найти сумму цифр числа N в С++

Число N может быть любым?? ? Какого типа: int, double, unsigned int, unsigned double?
#include <iostream>
using namespace std;

int main()
{
int n;
int sum=0;
cout << "please, enter n = ";
cin >> n;
while (n!=0)
{
sum += n % 10;
n /= 10;
}
cout << "sum = " << sum << endl;
return 0;
}
Игорь Бобров
Игорь Бобров
1 309
Лучший ответ
#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

void error();

int main()
{
setlocale(LC_CTYPE, "Russian_Russia.1251");
string str;
while (true)
{
system("cls");
cout << endl << " Введите целое положительное число: ";
cin >> str;
int size = str.length() + 1;
char * ptr = new char [size];
strcpy(ptr, str.c_str());
char number[2] = {'\0'};
int next, summa = 0;
for (int n = 0; n < size - 1; n++)
{
if (ptr[n] < '0' || ptr[n] > '9')
{
delete ptr;
error();
}
else
{
number[0] = ptr[n];
next = atoi((const char *) number);
summa += next;
}
}
delete ptr;
cout << endl << " Сумма цифр = " << summa;
cin.get(); cin.get();
}
return 0;
}

void error()
{
cout << "\a Данные не являются целым положительным числом! " << endl
<< " Повторите, пожалуйста ввод. ";
Sleep(2000);
main();
}
.N
. Nur1K . )))))
54 091
#include < iostream >
#include < math.h >
#include < conio.h >
using namespace std;

main() {
int n1=0,n;
printf ("Ввод числа: ");
cin >> n;
while (n!=0) {
n1+=n % 10;
n= n/10;
};
cout << n1;
getch();
return 0;
}
Максим Борисов
Максим Борисов
11 452
узнай сначала какое это число, тысяча, сотня или десяток, тада я те код смогу подсказать
Толик Гасанов
Толик Гасанов
8 401
Интересно другое, а на кого человек учится?

Если на программиста, тогда непонятно другое, неужели самому не интересно затылок почесать и придумать программу. Я не программист, но думаю сумел бы....
#include <iostream>
#include <locale>

#include <stdlib.h>
#include <time.h>
#include <math.h>

unsigned number_sum_digits(int number)
{
number = abs(number);

int sum = 0;
for ( ; number; number /= 10)
sum += number % 10;

return sum;
}

int main()
{
setlocale(LC_ALL, "");
srand((unsigned) time(NULL));

const int number = rand();

std::cout << "Number: " << number << std::endl;
std::cout << "Sum: " << number_sum_digits(number) << std::endl;

return 0;
}

Похожие вопросы