基于用户输入的停止循环迭代

本文关键字:循环 迭代 输入 于用户 用户 | 更新日期: 2023-09-27 18:36:37

我正在尝试制作一个简单的程序,该程序根据用户输入的速度和时间计算行驶的距离。它输出每小时行驶的每个距离,并将其输出到列表框。我不确定如何使循环在用户输入的时间停止迭代。我也不确定 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");
        }

    }
}

基于用户输入的停止循环迭代

时间需要成为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);
            }