Thread: Average value of recursive function

  1. #1
    Registered User
    Join Date
    Nov 2017
    Posts
    18

    Average value of recursive function

    This function returns the sum of "n" different values. (The running time of an algorithm) But I want the function to return the average value of all those values instead of the sum. Anyone got any ideas?

    Code:
    double sum(double alg, int n)
    {
    
        if (n == 1) {
            return alg;
    
        }
    
        return (alg + sum(alg,n-1));
    }

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Nope... this function returns 'n*alg', the average is 'alg'.

    And... if n <= 0 (n is a signed integer!) it will return 'alg*((2łą - abs(n)) + 2łą-2)'.
    Last edited by flp1969; 11-27-2019 at 10:10 AM.

  3. #3
    Registered User
    Join Date
    Nov 2017
    Posts
    18
    Quote Originally Posted by flp1969 View Post
    Nope... this function returns 'n*alg', the average is 'alg'.

    And... if n <= 0 (n is a signed integer!) it will return 'alg*((2łą - abs(n)) + 2łą-2)'.
    Nah it returns the sum. And "alg" is the function of the algorithm that also returns the "clock-time" of that specific algorithm. "n" are the number of times the function is asked to run.

  4. #4
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    If I understand what you're getting at, maybe something like this.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
     
    double func() {
        return (double)rand() / RAND_MAX * 3 + 10; // 10.0 to 13.0
    }
     
    double avg(double (*f)(), int n, double s, int i) {
        return i == n ? s / n : avg(f, n, s + f(), i + 1);
    }
     
    double sum(double (*f)(), int n) {
        return n == 0 ? 0 : f() + sum(f, n - 1);
    }
     
    int main() {
        srand(time(0));
        printf("%f\n", sum(func, 5));
        printf("%f\n", avg(func, 5, 0, 0));
    }
    A little inaccuracy saves tons of explanation. - H.H. Munro

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to getting average value of array in function ,
    By Veasna John in forum C++ Programming
    Replies: 2
    Last Post: 11-29-2014, 11:42 AM
  2. Converting recursive function to tail recursive
    By ajacobs365 in forum C Programming
    Replies: 1
    Last Post: 10-30-2011, 08:15 AM
  3. Replies: 1
    Last Post: 12-03-2010, 01:54 AM
  4. Make Recursive function 'Tail-Recursive'
    By dp2452 in forum C Programming
    Replies: 7
    Last Post: 12-04-2009, 10:13 AM
  5. average function length...
    By endo in forum C++ Programming
    Replies: 6
    Last Post: 08-16-2002, 04:12 PM

Tags for this Thread