I'm new to c++ and I've written a function which takes a and b as input and returns a raised to the power of b. I used templates for the function return data type and data type for a. but it fails to return the correct result for large numbers. I tried calculating pow(2,50) and it returns 0.
template <class numeric_type>
numeric_type pow(numeric_type a, int b) {
numeric_type result = 1;
for (int i = 0; i < b; i++) {
result *= a;
cout << result << i << endl;
}
return result;
}
And inside the main:
long long int powered = pow(2, 50);
cout << powered;
Yeah, that wont work. The numeric type of '2' is int. Use '2LL' for a long long int. The reason this isn't working is because 2^50 is too big to store within an integer (it's a 32bit number, but you would need 51bits to store 2^50)
auto powered = pow(2LL, 50);
Template arguments are deduced from function arguments being passed (but not return type); so given pow(2, 50);, numeric_type is deduced as int.
You can specify numeric_type explicitly,
auto powered = pow<long long int>(2, 50); // specify numeric_type as long long int explicitly
or add an explicit conversion on 2 to make it a long long int.
auto powered = pow(static_cast<long long int>(2), 50); // numeric_type is deduced as long long int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With