迭代因子实施 [英] Iterative Factorial Implementation

查看:132
本文介绍了迭代因子实施的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到多个迭代解决方案,在网络定义因子 N 。他们看起来是这样的:

I found multiple iterative solutions in the net for defining the factorial of n. They look something like this:

int Factorial(int number)
{
   int factorial = 1;

   for (int i = 1; i <= number; i++)
      factorial *= i;

   return factorial;
}

因子(0)= 1 因子(1)= 1 ?因此,里面的for循环的计数器变量应该从 2 ,因为它下面的一切都将产生 1

Doesn't Factorial(0) = 1 and Factorial(1) = 1? Therefore, the counter variable inside the for loop should start with 2 since everything below it will yield 1.

   for (int i = 2; i <= number; i++)
      factorial *= i;

是否有某种原因,他们所使用的 1 作为起始编号为计数器?

Is there some reason why they used 1 as the starting number for the counter?

推荐答案

没关系 - 1或2将工作,乘以1什么都不做。然而,大多数的循环开始与0或1,而这只是遵循模式。另外,阶乘的定义通常表示为所有的正整数直到n的产物,因此这包括一个。从本质上讲,1,美观,更好的起点。

It doesn't matter - either 1 or 2 will work, as multiplying by 1 does nothing. However, most loops start with 0 or 1, and this just follows the pattern. Also, the definition of factorial is often stated as the product of all positive integers up to n, so this includes one. Essentially, 1 is, aesthetically, a better starting point.

这篇关于迭代因子实施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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