简体   繁体   中英

C# - Factorial and power in one function

I have this simple code that based on a dropdown list. If Factorial is selected then type a number and submit and for power it is the same.

I have:

    double x;
    double y;
    double result;
    double m;
    int answer = 1;

    private void factorial(int num)
    {
        for(int x = 1; x <= num; x++)
        {
            answer = answer * x;
        }
    }


    private void pow(double x, double y)
    {
        m = Math.Pow(x, y);
        result = m;
    }

And the design:

        if(comboBox1.SelectedIndex == 0)
        {
            int fact;
            fact = int.Parse(textBox1.Text);
            factorial(fact);
            textBox2.Text = answer.ToString();
        }

        if(comboBox1.SelectedIndex == 1)
        {
            x = double.Parse(textBox1.Text);
            y = double.Parse(textBox3.Text);
            pow(x, y);
            textBox2.Text = Convert.ToString(result);
        }

So, how can I make pow() and factorial() into one function and do the same thing?

A bit messy, but it should do the job:

if(comboBox1.SelectedIndex == 0)
    {
        int fact;
        fact = int.Parse(textBox1.Text);
        factorialPow(fact, 0, 0, 0);
        textBox2.Text = answer.ToString();
    }

    if(comboBox1.SelectedIndex == 1)
    {
        x = double.Parse(textBox1.Text);
        y = double.Parse(textBox3.Text);
        factorialPow(0, x, y, 1);
        textBox2.Text = Convert.ToString(result);
    }

And:

private void factorialPow(int num, double x, double y, int selectedIndex)
        {
            switch (selectedIndex)
            {
                case 0:
                    for (int i = 1; i <= num; i++)
                    {
                        answer = answer * i;
                    }
                    break;

                case 1:
                    m = Math.Pow(x, y);
                    result = m;
                    break;
            }
        }

Disclaimer: I in no way condone this kind of coding, there are many, many ways to do this in a much cleaner, more efficient approach, but like I said it'll do the job.

Edit:

I also believe that what you posted was absolutely fine, you could add this extra method as a step between your functions, as so:

private void factorialOrPow(int num, double x, double y, int selectedIndex)
        {
            switch (selectedIndex)
            {
                case 0:
                    factorial(num);
                    break;

                case 1:
                    pow(x, y);
                    break;
            }
        }

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