0
How to find the sum of digits of an integer using c++?
its important...i have exam
4 Antworten
+ 6
int sum=0;int nums[]={1,2,3,4,5};/*find a way to split your num to this format…*/for(int stp=0;stp<nums.length;stp++){sum+=nums[stp];}
+ 2
yes i got a simple way
#include <iostream>
using namespace std;
int main() {
int n,rem,s=0;
cout<<"enter a number=";
cin>>n;
while(n>0)
{rem=n%10;
s=s+rem;
n=n/10;
}
cout<<"sum of digit is"<<s;
return 0;
}
+ 2
convert it to string, then use .length() method. If that's not the case, use modulus operator just like @Arjun has written.
+ 1
I'll give you a hint: any number modulo 10 will give you the last digit. For instance, 496 % 10 = 6.
While I'm at it, here's another: Every time you get a digit from the number, divide by 10 and round down. You can do this with the "floor()" function using the cmath header. Do it like this: n = (int) floor(n / 10).