0

我这里有一个逻辑问题。我想添加阶乘值的结果,但我不知道如何添加它们。这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Task_8_Set_III
{
    class Program                       
     {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 7; i++)
            {
                double c = i / fact(i);

                Console.WriteLine("Factorial is : " + c);
                Console.ReadLine();
                Console.WriteLine("By Adding.. will give " +);

            }
        }
        static double fact(double value)
        {
            if (value ==1)
            {
                return 1;
            }
            else
            {
                return (value * (fact(value - 1)));
            }
        }
    }
}
4

4 回答 4

1

您需要添加一个总变量来跟踪总和。

double total = 0; //the total

for (int i = 1; i <= 7; i++)
{
    double c = i / fact(i);
    total += c; // build up the value each time
    Console.WriteLine("Factorial is : " + c);
    Console.ReadLine();
    Console.WriteLine("By Adding.. will give " + total);

}
于 2010-01-22T17:12:50.937 回答
1

不确定这是否是您的意思,但是如果对于 N 的阶乘,您希望所有阶乘的总和达到该值,这就是您的操作方式。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Task_8_Set_III
{
    class Program                       
     {
        static void Main(string[] args)
        {
            double sum = 0;
            for (int i = 1; i <= 7; i++)
            {
                double c = i / fact(i);
                sum += c;
                Console.WriteLine("Factorial is : " + c);
                Console.ReadLine();
                Console.WriteLine("By Adding.. will give " + sum);

            }
        }
        static double fact(double value)
        {
            if (value ==1)
            {
                return 1;
            }
            else
            {
                return (value * (fact(value - 1)));
            }
        }
    }
}
于 2010-01-22T17:12:52.260 回答
0

没有完全理解你想要做什么,这里有两件事......

  • 在编程中,以下表达式是完全有效的: i = i + 1说“i 的新值是 i 的旧值加一”
  • 变量存在于范围内,它们的边界通常是大括号{ },也就是说,您将需要一个位于 foreach 大括号之外的变量,以便“记住”上一次迭代的内容。
于 2010-01-22T17:14:46.443 回答
0
   static void Main(string[] args)
            {
                int sum = 0;
                for (int i = 1; i <= 7; i++)
                {
                    int c = fact(i);
                    sum += c;
                    Console.WriteLine("Factorial is : " + c);
                    Console.ReadLine();
                    Console.WriteLine("By Adding.. will give " + sum);

                }
            }
            static int fact(int value)
            {
                if (value ==1)
                {
                    return 1;
                }
                else
                {
                    return (value * (fact(value - 1)));
                }
            }
于 2010-01-22T17:24:33.033 回答