【问题标题】:Factorials and finding the even factorial of them阶乘并找到它们的偶阶乘
【发布时间】:2014-07-22 19:41:16
【问题描述】:

我正在尝试让我的阶乘程序工作,它从用户那里获取一个数字并计算它的偶阶乘。即6!是 720,它的偶阶乘是 6x4x2 = 48,除了我已经弄清楚如何做阶乘部分但是每当我尝试添加更多代码以便我可以尝试计算其余部分时,我得到“运算符 % 不能应用于键入method groupint”或“在类、结构或接口成员声明中出现意外符号{”,我似乎看不出我做错了什么。任何建议都会有所帮助

using System;
namespace Factorial
{
    class Factorial
    {
        public static void Main()
        {
            Console.WriteLine("Enter a number");
            int i =int.Parse(Console.ReadLine());
            long fact = GetFactnum(i);
            Console.WriteLine("{0} factorial is {1}", i, fact);           
            Console.ReadKey();
        }

        public static long GetFactnum(int i)
        {          
            if (i == 0)
            {
                return 1;
            }
            return i * GetFactnum(i-1);
        }

     // public static void EvenFact()
     // {
     //     int sumofnums =0;   
     //     if((GetFactnum % 2) ==0)
     //         sumofnums += GetFactnum;
     // }
    }
}

【问题讨论】:

  • 花点时间阅读帮助中心的editing help。 Stack Overflow 上的格式设置与其他站点不同。您的帖子看起来越好,用户就越容易为您提供帮助。
  • 1- EvenFact 应该采用输入参数。 2-if((GetFactnum % 2) ==0) 是错误的。查看您之前的函数如何完成方法调用 3-GetFactnum 是您尝试做的一个很好的例子。 4- 阅读一些 c# 文档

标签: c# declaration factorial


【解决方案1】:

这是求奇数阶乘的一种方法:

int number = int.Parse(Console.ReadLine());
Console.WriteLine("Vlera e variables m: {0} \n", number);
  
long factorial = 1;
int i = 1;
Console.WriteLine(" x             f");
Console.WriteLine("---------------------------------");
while (i <= number)
{
    factorial *= i;
    if (i % 2 != 0)
    {
        Console.WriteLine(" {0}             {1}", i, factorial);
    }
    i++;
}
Console.WriteLine("----------------------------------");

【讨论】:

    【解决方案2】:

    编辑

    你有基本的想法,但有两件事是不正确的。

    首先,您的 GetFactnum % 2 部分语法不正确。你需要有int % int 的形式,你基本上给它一个method group % int。这就是您收到错误消息的原因。所以你必须使用GetFactun(int i) 的结果(或返回值)而不是方法名本身,像这样:

    int result = GetFactnum(i);
    if((result % 2) == 0)
    

    或者你可以立即使用返回值:

    if((GetFactnum(i) % 2) == 0)
    

    其次,我认为您想首先检查该值是偶数还是奇数。如果你传入一个奇数 i 会发生什么,它仍然计算偶阶乘吗?还是会报错?

    我编写该方法的方式与您为GetFactnum(int i) 所做的非常相似。但是这次你检查输入,看看它是不是奇数。其次,如果它是偶数,那么你知道一个偶数减去 2 将等于另一个偶数。

    public static long GetEvenFactorial(int i) {
        if((i % 2) != 0) 
        {
            throw new ArgumentException("Input must be even!");
        }
    
        if (i <= 0)
        {
            return 1;
        }
        return i * GetEvenFactorial(i - 2);
    }
    

    【讨论】:

    • 你给了 fish 并没有帮助 OP。
    • @ezi 你什么意思?上次我检查 SO.com 不是教育网站。这是一个问答网站。
    • 我知道这句愚蠢的说法,我认为它不适用于 StackOverflow.com,除非他们要求学习。
    • 伙计们,不要拒绝一个好的正确答案,即使它是一条鱼,也不酷。
    • @Ezi 如果您认为该问题与作业有关,请投反对票,而不是回答。我没有做错任何事,但给人的印象是答案不正确。
    猜你喜欢
    • 2020-09-23
    • 1970-01-01
    • 2014-03-24
    • 2015-04-19
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    相关资源
    最近更新 更多