Trouble with math outputs

So I've got this program that is supposed to give you the sum of the digits of a number. The problem is the output always comes out as zero.

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 <math.h>
using namespace std;

    char glados='y';
    int x, y=0.0;
    double z=0.0;
    
    int addDigits(double z)
    {
        y = x;
        while (y>0.0)
        {
            z+=y%(int)10.0;
            y/=10.0;
        }
    }
    
    int main ()
    {
        cout<<"Input a number: ";
        cin>> x;
        addDigits(z);
        cout<<"The sum of the digits is: " << z << "\n";
        cout<<"Want to try again?(y/n): ";
        cin>> glados;
        if (glados=='y')
        {
            main ();
        }
    }
Lets see:

Line 2. The standard library provides <cmath> for C++.
Besides, what do you use from that header? Nothing.

Line 3. Avoid this form. Use minimal amount of exposure:
1
2
using std::cout;
using std::cin;


Lines 5-7. Global variable. Avoid them. They have their place and use, when you really know that you have to use them. This is not the place.

Line 29. Thou shalt not call main(). Use a loop instead.
1
2
3
4
char glados = 'n';
do {
  // something
} while ( std::cin >> glados && 'y' == glados );


Line 14. The 'z' within the function is the function argument 'z', not the global 'z'.

Line 17. You do promise on line 9 to return an int, but you don't.

Line 23. You do call the addDigits with 'z'.

Line 23. You don't store the int returned by the function addDigits.

Line 9. The addDigits takes argument 'z' by value. A copy. It will not change the caller's parameter.
My first suggestion is that you stop using the global variables. Next why are you calling addDigits() with z as the parameter?

Second calling main() in a C++ program is not allowed, you need to investigate some of the proper loop constructs.

Topic archived. No new replies allowed.