我正在制作一个c#程序,将MPH +小时数转换为距离,然后将其显示在列表框中。
然而,当我运行我的程序时,它看起来更像是
你可以看到我的里程数没有增加,我的代码如下,
private void calculateButton_Click(object sender, EventArgs e)
{
double MPH;
double hourstraveled;
double distance;
MPH = double.Parse(vehicleSpeedTextBox.Text);
hourstraveled = double.Parse(hoursTraveledTextBox.Text);
distance = MPH * hourstraveled;
int count;
for (count = 0; count <= hourstraveled; count++)
displayListBox.Items.Add("After" + count + "Hours traveled you have gone" + distance + "Miles");
}
答案 0 :(得分:2)
您计算一次distance
值:
distance = MPH * hourstraveled;
你在循环的每次迭代中使用它:
for (count = 0; count <= hourstraveled; count++)
displayListBox.Items.Add("After" + count + "Hours traveled you have gone" + distance + "Miles");
但你永远不会重新计算它。因此,该值永远不会从初始计算值发生变化。
由于该值是动态的并且取决于count
值,因此您甚至根本不需要变量。只需动态计算即可。您在计算中甚至不需要hourstraveled
。也许这样的事情?:
for (count = 0; count <= hourstraveled; count++)
displayListBox.Items.Add("After " + count + " Hours traveled you have gone " + ((count + 1) * MPH) + " Miles");
虽然0小时后的距离不是0英里?:
for (count = 0; count <= hourstraveled; count++)
displayListBox.Items.Add("After " + count + " Hours traveled you have gone " + (count * MPH) + " Miles");