I have this code that returns the answer after raising a number to an nth number.
int getPower(int base, int x){
int result=1;
while (x != 0) {
result *= base;
--x;
}
return result;
}
I tried testing out where base is 97 and x is 5. I get a result of -2594335
. I tried changing my data type for the result to long but I'm still getting the same negative value.
As already it was mentioned in comments to your question an object of the type
int
can be not large enough to be able to store such values. So substitute the typeint
for the typelong long
.For example
The program output is
Instead of this statement
you can write
An alternative approach is to use for example the float type
long double
instead of the integer typelong long
as the type of the calculated value.