简体   繁体   中英

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;
    }

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".

You need validate the input first.If you are using a textbox..there should be a setting to accept only numbers.
Or
In the backend..you can check if the input is a number by using the code below

int n;
bool isNumeric = int.TryParse(FibonacciAsText.Text, out n);

if(isNumeric)
{
Your calculator code
}

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