Search code examples
c#fibonaccifix-protocol

c# Fibonacci calculator issue


i am trying to get a working Fibonacci calculator but i am having some issues. as far as i can tell my code is working well, although it crashes when i input a word. i'm unsure how i can get this to work for me so it will only accept numbers. Thanks in advance :D

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }


    private void Button_Click1(object sender, RoutedEventArgs e)
    {

        //Fibonacci

        string output = String.Empty;



        double result;
        double z = 0;
        double x = 1;
        double y = double.Parse(FibonacciAsText.Text);
        if (double.TryParse(FibonacciAsText.Text, out result))
        {
            if (y == 1)
                output = 1.ToString();
        }
        else if (y == 0)
        {
            output = 0.ToString();
        }
        for (double w = 0; w < y - 1; w++)
        {
            result = z;
            z = x;
            x = result + x;
            output = x.ToString();
        }
        Fibonacci.Text = output;
    }

Solution

  • This will exit the method and not allow the code to finish:

    double y;
    
    if (!double.TryParse(FibonacciAsText.Text, out y))
    {
        Fibonacci.Text = "N/A";
        return;
    }
    

    Basically, it's checking to see if you have a valid number. If so, it will set that as y (similar to Parse). If it doesn't succeed though, it will exit the method at "return".