2

(I have been newly introduced to the world of C# coding.) I am currently trying to work with the use of functions in the C# language. The program goal is to try to calculate the average using the total distance traveled and the total hours traveled and that will be multiplied by the time to get from NY city to MIAMI to get the distance from NY city to MIAMI.

How can i buld the functions(content wise) properly to give me the result(distance from NY city to MIAMI)? Should i make the function double void and declare them public or private?

4 Textboxes:

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

I have placed my functions which will be executed by a button click. A brief Idea of how I plan to use the functions:

 private void button1_Click(object sender, EventArgs e)
        {
            double v = Calculate_Velocity();
            double t = Get_Time();
            double d = Calculate_Distance (v,t);
            Display_Results(v, t, d);
            Clear_TextBoxes();


        }

4 Answers4

0

since i dont know the formulas i will just give you idea and you can build appication accordingly

just define function inside the class as

double i=0;
public double Calculate_Velocity()
{
    i=double.parse(Starting Mileage.Text)*double.parse(TotalDrivingTime.Text );
    return i;   
    //Formula may be wrong but you will get idea abt the things...
}

Likewise define all the functions...

Freelancer
  • 9,008
  • 7
  • 42
  • 81
0

Choosing double is fine if you want fractional miles. If you want a result back like 1500 or 1837 miles, then int is the way to go. By declaring it double, you will get a result back like 1500.33 miles (which would be 1500 miles and 1/3rd of a mile). So the choice is up to you if you want fractional miles (which is more precise) or whole number miles.

For your program, I'd make the functions private. Making them private means that the functions can't be called by instantiating an instance of your class. In other words, the end user wants just the end result. The end user doesn't have any business calling your "helper" functions.

Just as an FYI, you didn't ask but there is also a third visibility option called protected. Protected works just like private. The difference is, if your class is inherited by another class, that class has access to your protected functions and variables.

Icemanind
  • 47,519
  • 50
  • 171
  • 296
0

How can i buld the functions(content wise) properly to give me the result(distance from NY city to MIAMI)?

First off, there is no absolutely correct answer and everyone will have their own opinion. In my opinion, I would suggest adding a new class to your project.

class Formulas
{
    public static double CalculateVelocityFromMileage(double startMileage, double endMileage, double time)
    {
        return (endMileage - startMileage) / time;
    }
}

This isolates the logic of calculating velocity, distance, average time to a separate place and it makes no assumption about what you name your TextBox controls or how the user is expected to enter information into those text boxes.

You should make these functions static. You should think of a static function as one that only requires the inputs provided in the definition of the function. A static function is a good thing, it does not depend on items that are hidden from the view of the person calling your function. Of course, for static functions, you have no other choice but to return double.

And you should make the function public, this way the code in your click event can call it like this:

Formulas.CalculateVelocityFromMileage(start, end, time);

Remember the following:
1. A function should do one thing and do one thing well
2. A function should not rely on hidden values, its output should rely only on its arguments.

You might find yourself writing slightly more code, but you will thank yourself when you start writing more code as your application grows.

But trust your own instincts, and find your own personal style and discover what works for you.

Jason
  • 1,385
  • 9
  • 11
  • +1 This is a very good approach. How would I assign the value in the textBoxes to variables? –  Sep 25 '12 at 04:04
  • @charliercodex23 - Actually, the answer by TheJesterCrown has a great example of how to parse the user input into a double. The function "double.TryParse" has all the logic for turning a string into a number. It uses a syntax that might seem odd to you (being new to C#) called an "out parameter" This is just a fancy way of having a function return multiple values. But if you copy his example you should be good. I would put that code with your form's code. – Jason Sep 25 '12 at 04:11
0

You'll want to make the functions private, or protected. The difference between private and protected is that private can only be accessed by code in the class or struct, and protected can only be used in the current class, and any class derived from it.

This is a link to a good explanation of Access Modifiers in CSharp.

Your code should look something like this:

private double CalculateVelocity()
{
    double distance = 0;
    double time = 0;

    if(double.TryParse(tbDistance.Text, out distance) &&
       double.TryParse(tbTime.Text, out time))
    {
        return distance/time;
    }

    return 0.0;
}

private double GetTime()
{
    //Get Time
}

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
}

private void button1_Click(object sender, EventArgs e)
{
    //You get the idea
}

Since you're new to csharp this might be a good time to try using properties. GetTime for example can be written like this:

// Property to GetTime
public 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();
      }
}

And you can use the property like so:

double time = GetTime;

or

GetTime = time;

You might also consider using TimeSpan instead of a double for GetTime as well.

Community
  • 1
  • 1
TheJesterCrown
  • 138
  • 1
  • 8
  • +1 Thank you, much better aproach. My question now is how do I fill in the functions? for example in order to calculate velocity: `velocity = distance/time`. How would I put that inside the `CalculateVelocity()` function? –  Sep 25 '12 at 04:20
  • I updated the CalculateVelocity function above to show how you might write that function. You'll want to check your inputs which I haven't done here (i.e. Make sure time isn't 0). Of course a lot of it comes down to personal taste- most people would write CalculateVelocity so it took distance and time as parameters: `private double CalculateVelocity(double distance, double time)` – TheJesterCrown Sep 27 '12 at 02:34