variables - Count times Recursive was called C -
variables - Count times Recursive was called C -
i have function calculates geometric mean (nth root of product of terms, n number of terms), , thing i'm having problem figuring out how maintain track of how many terms there were. thing come global variable, know shouldn't that. how can without global variable?
float count; float geometricmean(float n) { char again; float j; printf("input number: "); scanf("%f", &j); printf("another number? (y/n) "); scanf(" %c", &again); if (again == 'y') { j *= geometricmean(n+1); if (n==1) homecoming pow(j, (1/count)); else { homecoming j; } } else { count = n; homecoming j; } }
use static variable. static variables don't alter between function calls. @ start of function, write like:
float geometricmean(float n) { static int count = 0; count ++; // rest of code; }
each time phone call function, count increment 1 (it won't go 0).
go here: what "static" mean in c program? if want know more static variables.
edit: please don't go out using static variables if global, smaller scope. lead undesired results! if you're planning alter value of static variable in each iteration of function, did here, please create sure create crystal clear alterations , utilize them right after defining static if possible.
c variables recursion count average
Comments
Post a Comment