根据用户输入停止循环迭代

时间:2016-02-26 23:40:57

标签: c# loops

我正在尝试制作一个简单的程序,根据用户输入的速度和时间来计算行进距离。它输出每小时行进的每个距离并将其输出到列表框。我不知道如何让循环在用户输入的时间停止迭代。我也不确定for循环是否是正确的循环使用。

private void calculateButton_Click(object sender, EventArgs e)
    {

        //decalre variables for speed, time, distance 
        double speed;
        double time;
        double distance;

        //declare constants to be used
        const int interval = 1;
        const int start_hours = 0;
        const int end_hours = 10;


        if (double.TryParse(speedTextBox.Text, out speed))
        {

            //try to get time from hours text box
            if (double.TryParse(hoursTextBox.Text, out time))
            {

                //display table of speeds
                for (time = start_hours; time <= end_hours; time += interval)
                {
                    //calculate distance driven 
                    distance = speed * time;

                    //display the distance driven in an amount of time
                    listBox1.Items.Add("After " + time + " hours, the distance traveled is " + distance);
                }
            }
            else
            {
                //invalid entry for hours
                MessageBox.Show("Invalid entry for time");
            }
        }
        else
        {
            //invalid entry for speed
            MessageBox.Show("Please enter MPH");
        }


    }
}

1 个答案:

答案 0 :(得分:0)

时间必须是for循环的限制。

  for (int i = start_hours; i <= time; i += interval)
            {
                //calculate distance driven 
                distance = speed * i;

                //display the distance driven in an amount of time
                listBox1.Items.Add("After " + i + " hours, the distance traveled is " + distance);
            }