想要从 Main 调用一个方法两次并显示两个输出

问题描述 投票:0回答:1

我想调用一个方法两次,用户必须输入两个正双精度数。 然后我希望将它们返回到 main() 并显示。 我不确定如何从主函数调用该方法,因为我只使用具有 1 种输入类型的方法来完成此操作。

       public static void Main(string[] args)
       {
        double costLitres = VolumeAndCost();
        }
        public static double VolumeAndCost(double costLitres)
       {
        double litresOfFuel;
        double costOfFuel;
        Console.WriteLine("Please Enter The Number Of Litres Of Full Put Into Car.");

        litresOfFuel = Convert.ToDouble(Console.ReadLine());
    
        if (litresOfFuel > 0)

        {
            return litresOfFuel;
        }

        else

        {
            Console.WriteLine("Please enter a positive value.");
            litresOfFuel = Convert.ToDouble(Console.ReadLine());

        }

        Console.WriteLine("Please Enter The Cost Of The Fuel In Dollars And Cents.");
        costOfFuel = Convert.ToDouble(Console.ReadLine());

        if (costOfFuel > 0)
        {
            return costOfFuel;
        }
        else
        {
            Console.WriteLine("Please enter a positive value.");
            costOfFuel = Convert.ToDouble(Console.ReadLine());
            return costOfFuel;

        }
c# methods calling-convention
1个回答
1
投票

我认为数量和成本太复杂,无法重复使用。它有多种作用。

你可以这样做:

using System;

public class Program
{

    public static void Main()
    {
        // ask the liters
        Console.WriteLine("Please Enter The Number Of Litres Of Full Put Into Car.");
        double liters = AskPositiveDouble();

        // ask the cost per liter
        Console.WriteLine("Please Enter The Cost Of The Fuel In Dollars And Cents.");
        double costOfFuel = AskPositiveDouble();

        // calculate costs
        double cost = VolumeAndCost(liters, costOfFuel);

        // output to the screen
        Console.WriteLine($"The price will be {liters * costOfFuel:f2}");
    }

    private static double AskPositiveDouble()
    {
        // loop
        while(true)
        {
            // if the user enters a double value, it continues checking.
            if(double.TryParse(Console.ReadLine(), out var value))
            {
                // if the value is positive, return that value
                if(value > 0)
                    return value;

                // otherwise show this information and repeat the input.
                Console.WriteLine("Please enter a positive value.");
            }
        }
    }

    private static double VolumeAndCost(double liters, double costOfFuel)
    {
        // calculation.
        return liters * costOfFuel;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.