本文介绍了For循环计算阶乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有这一套code和它意味着计算阶乘。

  INT numberInt = int.Parse(factorialNumberTextBox.Text);的for(int i = 1; I< numberInt;我++)
{
  numberInt = numberInt *我;
}factorialAnswerTextBox.Text = numberInt.ToString();

有关某种原因,它不工作,我不知道为什么。比如我会输入3,并得到答案-458131456这似乎很奇怪的。

任何帮助AP preciated。谢谢


解决方案

  INT numberInt = int.Parse(factorialNumberTextBox.Text);
INT结果= numberInt;的for(int i = 1; I< numberInt;我++)
{
    结果=结果*我;
}factorialAnswerTextBox.Text = result.ToString();

在一个侧面说明:这通常不会是计算阶乘的正确方法。
你需要输入一个检查,然后才能开始计算,如果你的初始值为1以下,在这种情况下,你需要手动返回1。

在另一个方面说明:这也是在那里递归方法可能是有用的一个很好的例子。

  INT因子(int i)以
{
    如果(ⅰ&下; = 1)
        返回1;
    回到我*因子(I - 1);
}

Currently I have this set of code and its meant to calculate factorials.

int numberInt = int.Parse(factorialNumberTextBox.Text);

for (int i = 1; i < numberInt; i++)
{
  numberInt = numberInt * i;
}

factorialAnswerTextBox.Text = numberInt.ToString();

For some reason it doesn't work and i have no clue why. For example i will input 3 and get the answer as -458131456 which seems really strange.

Any help appreciated. Thanks

解决方案
int numberInt = int.Parse(factorialNumberTextBox.Text);
int result = numberInt;

for (int i = 1; i < numberInt; i++)
{
    result = result * i;
}

factorialAnswerTextBox.Text = result.ToString();

on a side note: this would normally NOT be the correct way to calculate factorials.You'll need a check on the input before you can begin calculation, in case your starting value is 1 or below, in that case you need to manually return 1.

On another side note: this is also a perfect example of where recursive methods can be useful.

int Factorial(int i)
{
    if (i <= 1)
        return 1;
    return i * Factorial(i - 1);
}

这篇关于For循环计算阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-10 21:42
查看更多