/* write a function double power(double base, int exp) that finds and returns base^exp 0^0 returns 1 exp<0 base !=0 - function will not be called 2^(-3)=1/(2^3) in main test the function on 5 random pairs of base, exp and compare to the result of the math.h library function pow */ #include #include #include #include double power(double, int); //function prototype int main(){ srand(time(NULL)); int i, exp; double math_result, our_result,base; printf("enter base \n"); for(i=0;i<5;i++){ scanf("%lf",&base); //for exponent we will generate a random number between -5 and 5 exp= -5+rand()%11; if(exp<0 && base!=0){ math_result=pow(base, exp); our_result=power(base, exp); printf("math_result %f^%d %f\n",base, exp, math_result); printf("our result %f^%d %f\n",base, exp, our_result); } else if(exp>=0){ math_result=pow(base, exp); our_result=power(base, exp); printf("math_result %f^%d %f\n",base, exp, math_result); printf("our result %f^%d %f\n",base, exp, our_result); } else printf("invalid input\n"); } return 0; } double power(double base, int exp){ if(base == 0 && exp == 0) return 1; //base^exp=base*base*base....*base //exp<0 base^exp=1/(base*base*base....*base) int i; double product=1.0; for(i=0;i<(int)(fabs(exp)); i++) product*=base; if(exp>0) return product; else return 1/product; }