[英]How do I add the result of factorial values?
我在这里遇到逻辑问题。 我想添加阶乘值的结果,但不确定如何添加它们。 这是我的代码:
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)));
}
}
}
}
您需要添加一个总变量来跟踪总和。
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);
}
不确定这是否是您的意思,但是如果要让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)));
}
}
}
}
缺乏完全了解您想要确切执行的操作的两件事...
i = i + 1
说“ i的新值是i的旧值加一” { }
,也就是说,您将需要一个位于foreach括号之外的变量,以便“记住”上一次迭代的内容。 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)));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.