首页 > 解决方案 > 如何在 c# 中的特定行上重新启动?

问题描述

我是初学者,我尝试用 C# 创建一个简单的计算器。我想要的是,当你完成一个操作时,你可以重新启动或不重新启动。这是我的代码:

    using System;

namespace Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            // First number
            Console.WriteLine("Enter a number");
                double A = Convert.ToDouble(Console.ReadLine());
            // Second number
            Console.WriteLine("Enter another number");
                double B = Convert.ToDouble(Console.ReadLine());
            // Operator
            Console.WriteLine("Enter the operator");
                string C = Console.ReadLine();
                    // if you want to add
                    if(C == "+")
                    {
                        Console.WriteLine(A + B);
                    }
                    // if you want to remove
                    if(C == "-")
                    {
                        Console.WriteLine(A - B);
                    }
                    // if you want to multiply
                    if(C == "*")
                    {
                        Console.WriteLine(A * B);
                    }
                    // if you want to subdivide
                    if(C == "/")
                    {
                        Console.WriteLine(A / B);
                    }
            // Ask if they want to restart or finish
            Console.WriteLine("Want to do another operations? y/n");
                string W = Console.ReadLine();
                    // Restart
                    if(W == "y")
                    {
                        // Return at the beginning
                    }
                    // Finish
                    if(W == "n")
                    {
                        Console.WriteLine("Enter a key to close"); 
                            Console.ReadKey();
                    }
        }
    }
}

在这里你可以看到哪些,当你完成你的操作时,你可以重新启动(我不明白如何)或完成。我的代码(和我的演讲)效率不高(我是意大利人)我不擅长编程,我正在努力自学。

标签: c#

解决方案


您的问题的具体答案,如何跳到具体行是:goto 您放置一个标签myLabel:,然后当您想跳到那里时goto myLabel;

但是,goto 是邪恶的,必须避免,在大型程序中它使代码不可读并导致大量问题。

好的解决方案是创建一个循环并测试一个变量,如下所示:

bool execute = true;

while(execute)
{

    //..your calculator code

    Console.WriteLine("Want to do another operations? y/n");
    string W = Console.ReadLine();

    if(W == "n")
        execute = false;

}

这使得代码更加干净和可读。


推荐阅读