简体   繁体   English

For 循环只显示最后一个循环 C#

[英]For Loop Only Shows last Loop C#

How can I get the results to show each year and the year end value for each year?我怎样才能得到显示每年的结果和每年的年终价值?

double investment_decimal = Double.Parse(txtAmount.Text);
double rate_decimal = Double.Parse(txtRate.Text);
double years = Double.Parse(txtSlideValue.Text);
years = Convert.ToDouble(txtSlideValue.Text);
double calculation = 0;

        //for loop
            for (int i = 1; i < years + 1 ; i++)
            {

                calculation = investment_decimal * Math.Pow((1 + rate_decimal / years), (i));
                txtCalculation.Text = Convert.ToString("Year " + i.ToString() +"\t" + "Year End Value " + calculation.ToString("C")).PadRight(10);
            }

Your code makes multiple assignments to a UI element's text before letting UI refresh.在让 UI 刷新之前,您的代码对 UI 元素的文本进行了多次分配。 That is why only the last item remains visible;这就是为什么只有最后一项仍然可见; the rest of them get overwritten as you go through the loop.当你通过循环时,其余的会被覆盖。

You should prepare a string that corresponds to the entire string in the text box, and put it into txtCalculation.Text all at once:您应该准备一个与文本框中整个字符串相对应的字符串,并将其一次性放入txtCalculation.Text中:

StringBuilder sb = new StringBuilder();
for (int i = 1; i < years + 1 ; i++)
{

    calculation = investment_decimal * Math.Pow((1 + rate_decimal / years), (i));
    sb.AppendFormat("Year {0}\tYear End Value {1:C}\n", i, calculation);
}
txtCalculation.Text = sb.ToString();

Note the use of AppendFormat in place of string concatenation operator += with multiple values.请注意使用AppendFormat代替具有多个值的字符串连接运算符+= If you want to make a string, rather than appending to StringBuffer , you could use string.Format or interpolated strings of C# 6.如果你想创建一个字符串,而不是附加到StringBuffer ,你可以使用string.Format或 C# 6 的内插字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM