c++ - recursive tracing output sum of series -
why recursive method not giving me answer of 2.2833?
double m(int i) { if (i == 1) return 1; else return (1/i) + m(i -1); } int main() { double value=m(5); cout << value << endl; return 0; }
the answer 1?
because 1/1 1 , 1/2 = 0 (1/3 = 0 ....)
so need 1.0/(double) i
then 1.0 / 2.0 = 0.5
#include <iostream> double m(int i) { if (i == 1) return 1; else return (1.0/(double) i) + m(i -1); } int main(int,char**) { double value=m(5); std::cout << value << "\n"; return 0; }
Comments
Post a Comment