简体   繁体   English

c#中switch语句的伪代码

[英]Pseudocode for switch statement in c#

How do I write the pseudocode for a switch (case) statement in C#?如何在 C# 中为 switch (case) 语句编写伪代码?

switch (option)
{
    case 1:
        Console.Write("Enter First Number: ");
        num1 = Convert.ToDouble(Console.ReadLine());

        Console.Write("Enter Second Number: ");
        num2 = Convert.ToDouble(Console.ReadLine());

        result = num1 + num2;
        Console.WriteLine(result);
        break;

    case 2:
        Console.Write("Enter First Number: ");
        num1 = Convert.ToDouble(Console.ReadLine());

        Console.Write("Enter Second Number: ");
        num2 = Convert.ToDouble(Console.ReadLine());

        result = num1 - num2;
        Console.WriteLine(result);
        break;

    case 3:
        Console.Write("Enter First Number: ");
        num1 = Convert.ToDouble(Console.ReadLine());

        Console.Write("Enter Second Number: ");
        num2 = Convert.ToDouble(Console.ReadLine());

        result = num1 * num2;
        Console.WriteLine(result);
        break;

    default:
        Console.WriteLine("\n Next time follow instructions. You can only choose numbers 1 - 4");
        break;
}

So, if I was going to write this, I'd start with an enumerated type for the operations:所以,如果我要写这个,我将从操作的枚举类型开始:

public enum ArithmeticOperation
{
    Add,
    Subtract,
    Multiply,
    Divide,
}

I'd write a little helper function:我会写一个小助手函数:

 private static string ShowEnumOptions<T>() where T : struct
 {
     if (!typeof(T).IsEnum)
     {
         throw new ArgumentException($"Type: {typeof(T).ToString()} must be an enumerated type");
     }

     var options = Enum.GetNames(typeof(T));
     return string.Join("/", options);
 }

(the newest version of C# (which I don't use yet) allows a System.Enum constraint on a generic type parameter which would simplify this) (最新版本的 C#(我还没有使用)允许在泛型类型参数上使用 System.Enum 约束,这将简化这一点)

Then I'd write my main program to look like this:然后我会写我的主程序看起来像这样:

static void Main(string[] args)
{
    while (true)
    {
        ArithmeticOperation operation = default(ArithmeticOperation);
        var goodOperation = false;
        while (!goodOperation)
        {
            Console.Write(
                $"Enter operation (one of [{ShowEnumOptions<ArithmeticOperation>()}] or \"Quit\"): ");
            var response = Console.ReadLine();
            if (string.Equals(response, "Quit", StringComparison.InvariantCultureIgnoreCase))
            {
                return; //quit the app
            }

            if (Enum.TryParse<ArithmeticOperation>(response, true, out operation))
            {
                goodOperation = true;
            }
        }

        double value1 = 0.0;
        double value2 = 0.0;        //initialize them to keep the compiler happy
        var goodDouble = false;
        while (!goodDouble)
        {
            Console.Write("Enter the first number: ");
            var response = Console.ReadLine();
            if (double.TryParse(response, out value1))
            {
                goodDouble = true;
            }
        }
        goodDouble = false;
        while (!goodDouble)
        {
            Console.Write("Enter the second number: ");
            var response = Console.ReadLine();
            if (double.TryParse(response, out value2))
            {
                goodDouble = true;
            }
        }

        //ok, got an operation and two numbers

        double result = 0.0;
        switch (operation)
        {
            case ArithmeticOperation.Add:
                result = value1 + value2;
                break;
            case ArithmeticOperation.Subtract:
                result = value1 - value2;
                break;
            case ArithmeticOperation.Multiply:
                result = value1 * value2;
                break;
            case ArithmeticOperation.Divide:
                if (value2 == 0.0)
                {
                    Console.WriteLine("Division by zero is invalid");
                    result = double.NaN;   //NaN means "not a number"
                    break;
                }
                result = value1 / value2;
                break;
        }

        Console.WriteLine($"Result is {result}");
    }
}

Note that I check all input for validity.请注意,我检查了所有输入的有效性。 Always assume your users will enter bad data.始终假设您的用户将输入错误数据。 Also note that I check my double for equality with zero.另请注意,我检查了我的 double 是否与零相等。 Checking for floating point equality is usually a bad idea, but it's the right thing to do here.检查浮点相等性通常是一个坏主意,但在这里做是正确的。

Then, as pseudo code, all I'd write would be:然后,作为伪代码,我会写的是:

 // Get the operation (one of add/subtract/multiply or divide) - or allow the user to quit
 // Get each of value1 and value2 as doubles
 // Based on the operation, calculate the result (pay attention to division by zero)
 // Show the result
 // Loop back and let the user try again (or quit)

Pseudocode is basically writing what you're trying to do in comments.伪代码基本上就是在注释中写出你想要做的事情。 What your professor was probably trying to teach you is to make a bunch of comments to plan out the structure of your code, and then write your code.你的教授可能想教你的是做一堆注释来规划你的代码结构,然后编写你的代码。 What you have above is already functional code.你上面的已经是功能代码。 At the risk of answering your homework question, I'd say it goes something like this:冒着回答你的作业问题的风险,我会说它是这样的:

switch(option)
{
    case 1:
        //do something
        break;
    case 2:
        //do something else
        break;
    default:
        //what to do if none of the cases are met
        break;
} 

I don't know what you mean with pseudocode but this code is less repetitive:我不知道你用伪代码是什么意思,但这段代码不那么重复:

double result = 0;
Console.Write("Enter First Number: ");
double num1 = Convert.ToDouble(Console.ReadLine());

Console.Write("Enter Second Number: ");
double num2 = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Enter a number from 1 to 3");
string input = Console.ReadLine();

switch (input) {

    case "1" : 
        result = num1 + num2;
        break;
    case "2":
        result = num1 - num2;
        break;
    case "3":
        result = num1 * num2;
        break;  
    default:
    Console.WriteLine("\n Next time follow instructions. You can only choose numbers 1 - 4");
    break;

}
Console.WriteLine("Result = " + result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM