c++ - Why does for-loop behave differently when counting up vs counting down? -


this homework question revisited. requires me not use cmath , writes function evaluate cos pi/3. code is

#include <iostream> using namespace std;  double power(double x, int b) {     if (b>1) return x*power(x,b-1);     else if (b==0) return 1;     else return x; }  double cosine(double x, int k) {     double tmp=0;     (int n=0; n<=k; n++) {         tmp += power(-1,n) / factorial(2*n) * power(x,2*n);     }     return tmp; }  int main() {     double x=3.1415/3;      int k=100;     cout << cosine(x,k) << endl; } 

i have written 2 versions of double factorial(int a) for-loops.

one counts , outputs 0.500027 :

double factorial(int a) {     double tmp=1;     (int i=1; i<=a; i++) {         tmp*=i;     }     return tmp; } 

the other 1 counts down , outputs inf (but evaluate 4!=24):

double factorial(int a) {     double tmp=a;     (int i=a; i>=1; i--) {         tmp*=i;     }     return tmp; } 

why count down loop fail give convergent output?

the second factorial() multiplies a twice. try this:

double factorial(int a) {     double tmp=1; // use 1 instead of     (int i=a; i>=1; i--) {         tmp*=i;     }     return tmp; } 

note using double tmp=a; , initializing i a-1 not because make factorial(0) = 0, while factorial(0) should 1.

the first implementation multiplies 1 twice, multiplying 1 doesn't affect result.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -