简体   繁体   中英

Using goto statement

static void Main(string[] args)
{
    double i, j;
    Console.WriteLine("Enter fnum");
    i = Convert.ToDouble(Console.ReadLine());
    start:
    Console.WriteLine("Enter snum");
    j = Convert.ToDouble(Console.ReadLine());

    if(j==0)
    {
        goto start;
    }

    Console.ReadLine();
    Console.WriteLine("Div result is {0}/{1}={2}", i, j, i / j);
}

I'm trying to implement Divide by zero using GOTO in c#. I got the result but here I would like to first calculate fnum/snum and print the result and then if I enter snum zero it should ask me enter snum other than zero.Then the goto start label should start working. But here in this case I was only able to execute fnum/snum by default.

Console.WriteLine("Enter fnum");
i = Convert.ToDouble(Console.ReadLine());
start:
Console.WriteLine("Enter snum");
j = Convert.ToDouble(Console.ReadLine());

Here if I enter snum zero it should take me to start label and ask me "enter second number other zero"

Can any one help me?

if(j==0)
{
    Console.WriteLine("snum cannot be 0!!");
    goto start;
}

It is not recommended to use goto statements or get into the habit of using them.

They tend to increase complexity and create spaghetti code, they also affect readability as you add more and more of them. A bug caused by a goto statement can be tricky to fix. etc etc. others can edit more reasons not to use goto statements in if they wish.

You absolutely should NOT be using goto . Use a simple while loop instead:

static void Main(string[] args)
{
    double i, j = 0;
    Console.Write("Enter fnum: ");
    double.TryParse(Console.ReadLine(), out i);

    Console.Write("Enter snum: ");
    while (j == 0)
    {
        double.TryParse(Console.ReadLine(), out j);

        if(j==0)
            Console.WriteLine("Enter a number that is not 0");
    }


    Console.ReadLine();
    Console.WriteLine("Div result is {0}/{1}={2}", i, j, i / j);
}

Additionally, I have modified your code to use Double.TryParse instead of Convert.ToDouble() , as is generally recommended. With it, you can implement a check to make sure that the user has actually entered a number. I have also changed Console.WriteLine to Console.Write for the inputs, which doesn't affect the flow of the program at all, but to me makes it better aesthetically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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