I’ve been trying the cs50 credit problem and i am stuck in the part where you add every other digit in the number. This is what i came up with.
#include <iostream>
using namespace std;
int main() {
int num = 123456789;
int sum, last, second;
while (num>0)
{
last = num/10;
second = last%10;
num /=10;
cout<<second<<endl;
sum += second;
num /=10;
}
cout<<"sum: "<<sum<<endl;
return 0;
}
Output:
8
6
4
2
0
sum: 20
It works and gives the sum of every other digit which is 20 in this case. But it gives a very different answer when i add more values and change it to long.
This is where it gives a different result.
#include <iostream>
using namespace std;
int main() {
long num = 123456789;
long sum, last, second;
while (num>0)
{
last = num/10;
second = last%10;
num /=10;
cout<<second<<endl;
sum += second;
num /=10;
}
cout<<"sum: "<<sum<<endl;
return 0;
}
Output:
8
6
4
2
0
sum: 140736744828580
The answer should be 20 but it gives a really big number. I think the problem is my computation in the while loop but I can’t seem to find a solution which is why I posted it here. Thanks in advance.
Overpaint is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.