Reputation: 21
the code below is not working for if condition it directly entering into else.. if i give base value as 2 and power value as 3 it is showing result as 1..... how can i alter this to work properly....
class Program
{
static void Main(string[] args)
{
int i, a, result=1;
int b;
Console.WriteLine("enter the base value");
a=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter the power value");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("the vale of {0} to the power {1} is : {2}", a, b, result);
if(b>0)
{
for(i=1; i<=b; i++)
{
result=result*a;
}
}
else if (b<0)
{
for (i = 1; i <= b; i++)
{
result = 1 / (result * a);
}
}
else
{
result = 1;
}
Console.ReadLine();
}
Upvotes: 0
Views: 172
Reputation: 38795
Perhaps you might want to move the code that prints the result to happen after the calculation?:
if(b>0)
{
for(i=1; i<=b; i++)
{
result=result*a;
}
}
else if (b<0)
{
for (i = 1; i <= b; i++)
{
result = 1 / (result * a);
}
}
else
{
result = 1;
}
// happens after the calculation
Console.WriteLine("the vale of {0} to the power {1} is : {2}", a, b, result);
Please take some time to learn how to use a debugger to debug your code.
Microsoft have an introductory guide here and there's a tutorial on a third party site here.
Upvotes: 3