I've just begun learning C++ today and have some experience with other languages (Ruby). I'm understanding most of the basics, but I can't for the life of me figure out why this function (which returns the sum of the digits of an integer) only works correctly when I print the sum before returning the sum.
The code in question returns 32766 instead of 8:
#include <iostream>
#include <cmath>
using namespace std;
#include <string>
int sumOfDigits(int x) {
int i = 1;
int inc = 1;
while(i < x){
i *= 10;
inc += 1;
}
int size = inc;
int digs[inc];
inc = 0;
int z = x;
i /= 10;
while(z > 0) {
digs[inc] = (z/i);
z -= i * digs[inc];
i /= 10;
inc += 1;
}
int sum = 0;
for (inc = 0; inc < size; inc += 1) {
sum += digs[inc];
}
return sum;
}
int main(){
cout << sumOfDigits(125); // prints 32766
return 0;
}
but this piece of code that prints "hello world" before the return statement outputs 8 as expected.
#include <iostream>
#include <cmath>
using namespace std;
#include <string>
int sumOfDigits(int x) {
int i = 1;
int inc = 1;
while(i < x){
i *= 10;
inc += 1;
}
int size = inc;
int digs[inc];
inc = 0;
int z = x;
i /= 10;
while(z > 0) {
digs[inc] = (z/i);
z -= i * digs[inc];
i /= 10;
inc += 1;
}
int sum = 0;
for (inc = 0; inc < size; inc += 1) {
sum += digs[inc];
}
cout << "hello world";
return sum;
}
int main(){
cout << sumOfDigits(125);
return 0;
}