4

我刚刚被介绍到 C# 编码的世界。目前,我正在编写程序,该程序将使用总行驶距离和总行驶小时数计算平均速度,该结果将乘以从纽约市到迈阿密的时间,以获得从纽约市到迈阿密的距离。我textBoxes在表格上放了四个,一个button用来计算。

我需要帮助构建功能。例如,为了计算速度:速度=距离/时间。我如何将这些信息以正确的格式放入 CalculateVelocity() 函数中?

4 个文本框及其标签(这是用户输入数据的地方):

Starting Mileage
Ending Mileage
Total Driving Time 
Time from NY city to MIAMI

我正在使用的代码功能:

 private double CalculateVelocity()
    {
        //Calculate Velocity
    }

    public double GetTime()
    {
            //Get Time
            return GetTime;
    }

    private double CalculateDistance(double velocity, double time)
    {
        //Calculate Distance
    }

    private double DisplayResults(double velocity, double time, double distance)
    {
        //Display Results
    }

    private double ClearTextboxes()
    {
        //Clear textboxes
    }

    // Property to GetTime
   private double GetTime
        {
            get
            {
                // variable to hold time
                double time = double.MinValue;

                // Safely parse the text into a double
                if (double.TryParse(tbTime.Text, out time))
                {
                    return time;
                }

                // Could just as easily return time here   
                return double.MinValue;
            }
            set
            {
                // Set tbTime
                tbTime.Text = value.ToString();
            }
        }

    private void button1_Click(object sender, EventArgs e)
    {
        //Calculate and display result in a label
    }
4

2 回答 2

3

CalculateVelocity应该是这样的:

private double CalculateVelocity()
{
     double time = GetTime(); //assuming you have set up GetTime()
     double distance = endingMileageBox - startingMileageBox;
     return distance/time; 
}

其中endingMileageBox是结束里程文本框startingMileageBox的值, 是起始里程文本框的值。


根据您的评论,这CalculateDistance应该是这样的:

private double CalculateDistance(double velocity, double time)
{
    //note that this assumes the units match up. If not, you'll need to do some conversions here
    return velocity * time;
}    

}

于 2012-09-25T13:48:30.127 回答
2

只需添加您需要的参数,并在调用应该像这样的函数之前从文本框中进行解析(正如您所展示的那样):

private static double CalculateVelocityMPH(double distanceMiles, double timeHours) 
{ 
    return distanceMiles / timeHours;
}

值得选择和指定像我一样作为后期修复的单位。

然后在解析时间文本框时,使用TimeSpan.Parsethen.TotalHours来调用方法。

于 2012-09-25T13:45:43.913 回答