简体   繁体   中英

How to recursively calculate the average of digits

I need to calculate the average of digits.

For example: n = 123, average = (1+2+3)/3=2

So far I have managed to correctly calculate the sum, but I am having problems with getting the number of the digits in order to calculate the average. I would use 2 recursion methods to calculate the sum and number of digits, but I am only allowed to use 1 recursion method. I am also not allowed to use any global variables

public static int avg(int n, int sum, int i) {
    if(n==0)
        return 0;
    sum =  n%10+avg(n/10, sum, i);
    i++;
    return sum/i;
}

There is no need for multiple recursive methods. You need to pass the sum and count of digits through the recursive method itself. Because you can only return one variable, it's simplest to have the base case return the average.

Also, calculate the average as a double to avoid integer division truncating your answer.

public static double avg(int n, int sum, int i) {
    if(n==0)
        return (double) sum / i;
    return avg(n / 10, sum + n % 10, i + 1);
}

The base case returns the sum divided by the count that has accumulated so far. Else, for the number n , pass n / 10 to take off the ones digit. For sum , add the last digit to the sum. For i , increment the count.

Something like this would work.

public static double avg(int n, int sum, int i) {
    if(n==0)
        return (double) sum/i;
    return avg(n/10,sum + n%10,i+1);
}

Calling with avg(123,0,0) .
With each recursion you increase the sum by the digit and increase i by 1 as the counter for the number of digits.

I like to write a front-end method for cases like this, to help end-users avoid the need to remember to use magical mystery values for the additional parameters needed by the recursion:

private static double avg(int n, int sum, int count) {
    if(n == 0)
        return (double) sum / count;
    return avg(n / 10, sum + n % 10, count + 1);
}

public static double avg(int n) {
    if (n == 0)
        return 0.0;
    return avg(n, 0, 0);
}

This allows you to set up default values for the recursive calculation without exposing them to the public. This version also guards against the input being 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM