Separate integer numbers?

Hi every one
There is a question that says: let the user input any integer number and then separate it and then add the individual numbers together for the summation
and here what I did .. but there is a problem .. some times the last number become less by 1 ... for example if I enter 1234 .. it displays 1 2 3 3
here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
#include<cmath>
using namespace std;
int main ()
{
	int no,tst(1),pwr(-1),res,sum(0);
	long double first(10),sav;
    cout << "Enter any integer number"<<endl;
    cin>>no;
    cout<<"The Individual digits of "<<no<<" are : ";
	tst = no;
	sav= no;
	while (tst!=0)
	{
		pwr= pwr + 1;
		tst= tst/10;
	}
	sav=no/pow( first,  pwr);
	while(pwr>=0)
	{
	res= sav;
	pwr--;
	cout<<res<<" ";
	sav = sav - res;
	sav = sav*10;
	sum= res+sum;
	}
	cout<<endl;
	cout<<"The Sum is :"<<sum<<endl;
	return 0;
}


Can any one tell me what's wrong with it?

Thanx
Last edited on
I can't say why that happens, maybe it's due to float imprecision.
Anyway, you're overcomplicating this.
1
2
do std::cout << num%10 << '\n';
while(num/=10);
so how can I solve float imprecision?
the example that you put reverses the number ... 1234 .. it outputs 4 3 2 1 but I want 1 2 3 4
Thanks :)
you cant. double is as most precision as possible.

but here is another solution, using string and stringstream.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main ()
{
    int sum = 0;

    string input;

    cout << "Enter any integer number" << endl;
    cin >> input;
    cout<<"The Individual digits of " << input << " are : ";

    for (size_t i = 0; i < input.length(); i++) {
        cout << input.at(i) << " ";
        stringstream ss(input.substr(i, 1)); //generates a string with the current diget as its content
        int x;
        ss >> x;
        sum += x;
    }

    cout << "The Sum is :" << sum << endl;
    
    return 0;
}
you cant. double is as most precision as possible.

There's still long double though. And __float128 in gcc.

And using stringstreams is unnecessary in this case. You can directly convert an ASCII digit character to a number by substracting 48 from it. And even then you would only have to do that in the first place when you wanted to add the digits of a floating point number, the example hamstermann gave works just fine with integers.
Topic archived. No new replies allowed.