For 循环计算阶乘 [英] For loop to calculate factorials

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

问题描述

目前我有这组代码,用于计算阶乘.

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();

由于某种原因它不起作用,我不知道为什么.例如,我将输入 3 并得到答案为 -458131456,这看起来很奇怪.

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();

附带说明:这通常不是计算阶乘的正确方法.在开始计算之前,您需要检查输入,如果您的起始值为 1 或以下,则您需要手动返回 1.

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 循环计算阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆