2017-09-24 17 views
0

我寫在C#一個簡單的程序,當你給一個X和Y(X^Y)是計算一個數字的力量。答案顯示在一個文本框中。例如:X = 2,Y = 5文本框中的答案是:權力在字符串中的C#

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

我的問題是,我該怎麼做纔能有這樣的結果:

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 

這裏是我的代碼:

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; 
    } 
} 

數字1是X.

NUMBER2爲Y

+1

請提供代碼作爲文本而不是圖片。 –

+0

當您嘗試打印第二個號碼並重新打印第一個號碼時,您有一個錯字。 – kenny

+2

一個例子,其中原始值是* other * than 1將會更容易理解。 –

回答

0

需要很多改進,但類似的東西?

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 
+0

是的,正是我在找的東西。謝謝。 – Hollow

+0

如果您發現自己在循環中連接了字符串,最好使用StringBuilder。 –

+1

你應該紀念他的答案,因爲接受的答案.. –