2016-10-05 44 views
-3

我遇到了while循环的问题。我被要求编写一个程序,让用户输入两个数字,例如1和11.我需要该程序在输出中显示1,2,3,4,5,6,7,8,9,10,11标签,但我无法弄清楚..这是我迄今为止。虽然循环输出数字有问题

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void whileButton_Click(object sender, EventArgs e) 
    { 
     double variableOne = 0; 
     double variableTwo = 0; 
     int i = 0; 

     //Get number 
     if (double.TryParse(variableOneText.Text, out variableOne)) 
     { 
      if (double.TryParse(variableTwoText.Text, out variableTwo)) 
      { 
       while (variableOne <= variableTwo) 
       { 
        i = i + 1; 
        outputLabel.Text = i.ToString(); 
       } 
      } 
      else 
      { 
       MessageBox.Show("Please enter a number"); 
      } 

     } 
     else 
     { 
      MessageBox.Show("Please enter a number"); 
     }  
    } 
} 
+0

_“我需要该程序显示1-11”_ - 意思是什么,究竟是什么?你真的想要的文字'1-11'?你希望每个值都按顺序出现吗?还有别的吗?你的问题很不清楚。如果你被老师要求写这篇文章,请考虑向他们寻求帮助,因为他们能够给出比我们任何人更好的关于特定主题的建议。如果你想在这里得到答案,请修正你的问题,以便你准确地解释你想要程序做什么。 –

+0

你好。我需要显示的字面数字1,2,3等。我只是有一些麻烦,找出我需要用来做到这一点的表达。 – user6923913

+0

你还不清楚。你想让文字阅读“1,2,3等”吗?你想让文本阅读'1,2,3,4,5,6,7,8,8,10,11'吗?你想让文本阅读'1',然后'2',然后'3',依此类推? **请[编辑您的问题](http://stackoverflow.com/review/suggested-edits/13885385),以便清楚您正在尝试做什么,以及您遇到问题解决的具体问题。**准确解释现在程序做了什么,并且正如你所希望的那样解释。请参阅[问]以获取更多关于如何以清晰,可回答的方式展示您的问题的信息 –

回答

0

你有没有改变你的variableOne所以一切的时候,variableOne<variableTwo和而永不断线。

如果你想使用variableOne削减variableTwo,你可以使用

double temp = variableOne ; 
variableOne = variableTwo ; 
variableTwo = temp ; 

variableOne < variableTwo

0

更改与下面的一个while循环:

var sb = new StringBuilder(); 
while (variableOne <= variableTwo) 
{ 
     sb.Append(string.Concat(variableOne,",")); 
     variableOne  = variableOne + 1; 

} 
outputLabel.Text = sb.ToString().Remove(sb.ToString().Length-1)); 
+0

这有帮助,但它只显示我的第一个号码,它没有显示所有的介于两者之间..例如,我在变量1文本框中输入1,在变量2中输入4,但它只显示了4.不是1,2,3,4就像我想 – user6923913

+0

我更新了我的答案。请注意,您的问题最好是在控制台应用程序中实现。我不确定为什么选择Windows Form应用程序来构建它?无论如何,如果它帮助你,请将它标记为“答案”。谢谢 – AKR

0

您的代码因为它有两个问题。首先,在首次分配variableOnevariableTwo之后,您永远不会更改它们的值,因此当您输入while循环时,它永远不会结束,因为variableOne <= variableTwo总是为真。您需要使用其值会更改的变量才能正确使用循环。

其次,outputLabel.Text = i.ToString();您不是将文本添加到标签的末尾,而是完全替换它。如果你的循环是功能性的,这会导致你最终结束,而不是“1,2,3,4,...,11”,而只是“11”。

int variableOne; 
int variableTwo; 

if (int.TryParse(variableOneText.Text, out variableOne)) 
{ 
    if (int.TryParse(variableTwoText.Text, out variableTwo)) 
    { 
     StringBuilder sb = new StringBuilder(); 

     for (int i = variableOne; i <= variableTwo; i++) 
     { 
      if (sb.Length > 0) 
       sb.Append(","); 

      sb.Append(i); 
     } 

     outputLabel.Text = sb.ToString(); 
    } 
    else 
    { 
     MessageBox.Show("Please enter a number"); 
    } 
} 
else 
{ 
    MessageBox.Show("Please enter a number"); 
}