如何在C#中使用不同方法的方法/调用?

时间:2017-07-20 15:27:25

标签: c#

我正在尝试编写一个程序,将用户输入的英寸数转换为英尺,码和英里。下面是我的工作代码,但是,我需要将每个转换(英尺/码/英里)分成不同的方法,这些方法将从main调用。我怎样才能做到这一点?

class Program
{
    static void Main(string[] args)
    {

        int feet = 12;
        int yards = 36;
        int miles = 63360;


        Console.WriteLine("How many inches would you like to convert?");
        int inches = Convert.ToInt32(Console.ReadLine());

        double numOfFeet = (double)inches / feet;
        double numOfYards = (double)inches / yards;
        double numOfMiles = (double)inches / miles;

        Console.WriteLine(inches + " inches is equivalent to " + string.Format("{0:N2}", numOfFeet) + " feet, or " + string.Format("{0:N2}", numOfYards) + " yards, or " + string.Format("{0:N2}", numOfMiles) + " miles.");
        Console.ReadLine();


    }
}

4 个答案:

答案 0 :(得分:0)

这应该是:

Set<Set.Element>

你的主人会简单地称他们为:

static double ConvertInchesToFeet(double inches){
     //code for inches to feet
}

static double ConvertInchesToYards(double inches){
     //code for inches to Yards
}

static double ConvertInchesToMiles(double inches){
     //code for inches to Miles
}

答案 1 :(得分:0)

你可以不做这样的事吗?

注意每次只传入Inches的新方法的逻辑抽象并返回一个double类型。

  static void Main(string[] args)
    {
        Console.WriteLine("How many inches would you like to convert?");
        int inches = Convert.ToInt32(Console.ReadLine());

        double numOfFeet = ConvertToFeet(inches);
        double numOfYards = ConvertToYards(inches);
        double numOfMiles = ConvertToMiles(inches);

        Console.WriteLine(inches + " inches is equivalent to " + string.Format("{0:N2}", numOfFeet) + " feet, or " + string.Format("{0:N2}", numOfYards) + " yards, or " + string.Format("{0:N2}", numOfMiles) + " miles.");
        Console.ReadLine();

    }

    private static double ConvertToMiles(int inches)
    {
        int miles = 63360;
        return inches / miles;
    }

    private static double ConvertToYards(int inches)
    {
        int yards = 36;
        return inches / yards;
    }

    private static double ConvertToFeet(double inches)
    {
        int feet = 12;
        return inches / feet;
    }
}

答案 2 :(得分:0)

您需要使用静态方法。它们看起来像这样:

static double InchesToFeet(int inches)
{
    return (double)inches / 12;
}

static double InchesToYards(int inches)
{
    return (double)inches / 36;
}

static double InchesToMiles(int inches)
{
    return (double)inches / 63360;
}

要调用它们,您只需在主体中使用方法调用,如下所示:

double result = InchesToFeet(inches);

答案 3 :(得分:0)

您可以通过两种方式在控制台应用程序中完成此任务:

  • 创建方法以进行计算并从方法中写入控制台。
  • 创建函数以返回答案并在Main方法中写入控制台。

使用控制台应用程序时,请务必注意该类是静态类。因此,如果要在控制台应用程序中定义静态方法/函数,则需要静态方法/函数。

因此,选项1:

static void CalcuateFeet(int inches)
{
    Console.WriteLine("Inches as feet:" +  ((double)inches) / 12.0;
}

选项2:

static double CalcuateFeet(int inches)
{
    return ((double)inches) / 12.0;
}