c++ - Power function in a loop -
i need writing power function. so, need write porogramm, output table 1 10 in power in loop. not using pow or exp example of output:
0^0 == 1 1^1 == 1 2^2 == 4 3^3 == 27 4^4 == 256 (and on, to) 10^10 == 10000000000
not using cmath (no pow or exp)
for example:
e.g. power( 3.0, 5 ) return 243 because 3*3*3*3*3 243 e.g. power( 173, 0 ) return 1 because number raised power of 0 1.
i did simple loop, have no idea how insert power formula in it. thinking while loop
#include <iostream> #include <string> using namespace std; int main(){ int number = 0, tot; (int table = 0; table < 10; table++) { tot = number * table; cout << tot << endl; number++; } }
this recursive function can calculate value raised integer power
double power(double base, unsigned int exp) { if (exp == 0) { return 1.0; } else { return base * power(base, exp - 1); } }
an iterative method be
double power(double base, unsigned int exp) { double product = 1.0; (unsigned int = 0; < exp; ++i) { product *= base; } return product; }
you can test either method like
int main() { std::cout << power(5, 3); }
output
125
Comments
Post a Comment