I'm relatively new to programming in C#. I'm building an exponent calculator, and I got it working, but while debugging I came across an issue that I do not understand why I get the output that I get.
This is the class and method in question when I get the output I know is wrong. (note i did later fix it by making it total *= lower
in the for loop)
using System;
namespace stars
{
public class Exponent
{
public int Exp(int lower, int power)
{
int total = lower;
if ( power == 0 )
{
//returns 1 for any exponent of 0
Console.WriteLine(" 1");
return 1;
}
else if ( lower == 0 )
{
//returns 0 for any base of 0
Console.WriteLine("0");
return 0;
}
else if ( ( power % 1 ) == 0 ) // check for integer exponent
{
for ( int i = 1; !( i > power ); i++ ) //math
{
lower *= lower;
}
Console.WriteLine(lower);
return total;
}
else
{
Console.WriteLine("error");
}
}
}
}
at the last elseif, where I have my forloop, to (incorrectly) calculate the value of some integer to the power of another integer, I (incorrectly) perform the calculation lower = lower * lower, where lower is the base number.
i.e. 5^4,, 5 = lower, 4 = power
anyways, when I run it at 5^4, the result is 0. Why does it come out to 0? I figured it would work like this
5 * 5 = 25 ---> 25 * 25 = 625 ----> 625 * 625... etc
or is the end value so large that the compiler spits out 0.