Hollow - 5 months ago 27
C# Question

# Powers in string in C#

I wrote a simple programme in C# that calculate the power of a number when you give a X and Y (X^Y). The answer is showed in a textbox. For example : X=2 and Y=5 the answer in the textbox is:

``````2 X 2 = 32
2 X 2 = 32
2 X 2 = 32
2 X 2 = 32
2 X 2 = 32
2 X 2 = 32
``````

My question is how can I do to have this result:

``````2 X 2 = 2
2 X 2 X 2 = 8
2 X 2 X 2 X 2 = 16
2 X 2 X 2 X 2 X 2 = 32
``````

Here is my code:

``````private void button1_Click (object sender, EventArgs e)
{
double number1;
doubLe number2;
int count = 0;

double power;
number1 = double.Parse(Txtnumber1.Text};
number2 = double.Parse(Txtnumber2.Text};

while (count < number2)
{
power = Math.Pow(number1, number2);
Txtanswer.Text = Txtanswer.Text + number1.ToString() + " " + " x" + " " + number1.ToString() + " " + "=" + power.ToString() + "\r\n";
count += 1;
}
}
``````

Number1 is X.

Number2 is Y

needs lots of improve but something like that ?

``````class PowBuilder
{
public static string PrintNumber(double number, double times)
{
string temp = "";
for(int i = 1;i < times; i++)
{
temp += number.ToString() + " x ";
}
return temp;
}

}
class Program
{
private static string PowFan(double a, double b)
{

int count = 1;
double power;
string sb = "";

while (count < b)
{
power = Math.Pow(a, count);
sb += PowBuilder.PrintNumber(a, count) + a.ToString() + " = " + power.ToString() + " \r\n";
count += 1;
}
return sb;
}
static void Main(string[] args)
{
Console.WriteLine(PowFan(2, 15).ToString());
}
}

//output
//2 = 2
//2 x 2 = 4
//2 x 2 x 2 = 8
//2 x 2 x 2 x 2 = 16
//2 x 2 x 2 x 2 x 2 = 32
//2 x 2 x 2 x 2 x 2 x 2 = 64
//2 x 2 x 2 x 2 x 2 x 2 x 2 = 128
//2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 = 256
//2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 = 512
//2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 = 1024
//2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 = 2048
//2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 = 4096
//2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 = 8192
//2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 = 16384
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download