Calculating Sum

Well I can get the sum every time the user inputs an integer until they either input a negative number, or put a non-integer character. Problem: My sum calculations are slight off. Starts on line 24 & attempted output at 30. I just want to know why it's not adding correctly, so I can rework on my sum calculations
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <cstdlib>
 
using namespace std;
 
int main()
{
    int j , i = 0, k = 0,number;
	double sum = 0;
    cout << "Enter Positive integer number: ";
    while(cin >> number)
    {
		
        cout << endl;
        if( number < 0)//test if the number is negative
        {
			cout << "Ending program since user has input a negative number" <<endl;
            break;
        }
        int temp = number;
        int p = 1;
        while( temp > 0) //counting number of digits
        {
			sum = sum+temp;	//Sum attempt.
            temp /= 10;
            p *= 10;
            i++;

        }
				cout << sum << endl;

        j = i % 3;
        p /= 10;
        while( i > 0 )//display integer number with 1000 seperator
        {

            cout << char ((number/p) +'0');
            number %= p;
            p /= 10;
            i--;
            k++;
            j--;
            if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2) )
            {
                cout <<",";
                k = 0;
            }
        }
        cout << endl << endl;
        cout << "This program will exit if you input any non-integer characters\n";
        cout << "Enter another integer number: ";
    }

    return 0;
}
Last edited on
I don't quite understand. But is it your expected output?


Enter Positive integer number: 5000

Sum : 5000
Number with 1000 seperator : 5.000

This program will exit if you input any non-integer characters
Enter another integer number: 250000

Sum : 255000
Number with 1000 seperator : 255.000
Heya Kikiman.
If I input 5000, the sum outputs 5555
and again with 250000, sum total is now 283332

i'm sure i'll figure this out
Try moving line 24 to before while()
*shrugs* thanks Icedoe lol ;/. works now. ;P
No problem. noob myself;)
Topic archived. No new replies allowed.