Digital root problem

Jul 1, 2015 at 10:20pm
Hi, I'm a beginner in c++ and need some help in my code.
I tried to write the code below for the program that asks a user to enter a number in the range 1-99 an outputs digital root of the number entered.
But it doesn't work properly. I've found some codes to write such program, but
I'd like to know what is wrong with my code. Can anyone please explain in what part I have a mistake ?

Thanks in advance !


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
56
57
58
59
60
61
62
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }

int sum_of_digits (int number)
{
	int digitSum = 0;

	for (int i=1; i<=2;++i)
	{
			
		digitSum+=number%10;
		number /=10;
		
	}
	return digitSum;
}

int sum_of_digits_2 (int number_2)
{
	int digitSum_2 = 0;
	
	for (int x=0; x<=1;++x)
	{
		digitSum_2+=sum_of_digits(number_2)%10;
		int n = sum_of_digits(number_2);
		n /=10;
	}
				
	cout << "Digital root is: " << digitSum_2 << endl;
}

int main()

{
	cout << "To terminate the program press '0'.\n";
	cout << "\nEnter a number (1-99): ";
	vector <int> values;
	for (int val;cin >> val;)
	{
		values.push_back(val);
	
			
		if(val != 0)
		{
			sum_of_digits_2(val);
			cout << "\nEnter a number (1-99): ";
		}
		else
		{
			break;
		}
		
	}
	
	
    return 0; 
}
Jul 1, 2015 at 10:59pm
Do you need to calculate digital root only, or calculate it in a specific way?

Because digital root is ((n - 1) % 9 + 1)
Jul 2, 2015 at 12:20pm
Thank you for the answer, but I'd like to know why my code outputs wrong results. I repeated the same operation twice (calculating sum of digits) using one function in another. But it outputs wrong results, for example, for 75 digital root is 3, but I get 4. And yes I would like to calculate it in this way.
Jul 2, 2015 at 1:21pm
The problem is that you caclulate the sum of number_2 in sum_of_digits_2(...) twice, but you need the sum of the last calculated the second time. This only when the result from the last calculation was greater nine.
Jul 3, 2015 at 2:19pm
Ok, thank you coder777, I'll think about how to modify the code.
And thank you MiiniPaa.
Topic archived. No new replies allowed.