加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用循环计算C#中的阶乘

发布时间:2020-12-16 01:53:23 所属栏目:百科 来源:网络整理
导读:这是我到目前为止: namespace factorials{ class Program { static void Main(string[] args) { int number; do { Console.WriteLine("What non-negative integer do you want to factorial?"); while (!int.TryParse(Console.ReadLine(),out number)) Cons
这是我到目前为止:

namespace factorials
{
    class Program
    {
        static void Main(string[] args)
        {
            int number;

            do
            {
                Console.WriteLine("What non-negative integer do you want to factorial?");
                while (!int.TryParse(Console.ReadLine(),out number))
                    Console.WriteLine("Please enter a whole number only");
                calculate(ref number);
            } while (number >= 0);
            Console.WriteLine("Please enter a non-negative number");

        }
        static void calculate(ref int number)
        {
            int factorial;
            int counter;

            for (counter = number; counter <= number; counter++)
            {
                factorial = number * number;
                Console.WriteLine("The factorial of {0} is {1}",number,factorial);
            }

    }
    }
    }

现在它只是给了我数字的平方,而不是它们的阶乘.如何使其作为输入重复次数,从而导致因子?

此外,我不确定是否有必要将程序仅限制为非负整数,但如果我想要那个部分只是在那里结束程序而不是循环回到开头.

解决方法

你的循环将数字的平方分配给循环中的结果,然后立即退出.您需要对其进行更改,以便将结果重复乘以1到N(包括1和N)之间的数字.

将1分配给阶乘,并将其乘以循环中的计数器:

factorial *= counter;

别忘了在1开始你的柜台.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读