I'm having a logic problem here. I want to add the result of the factorial values but I'm not sure how to add them. Here's my code:
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)));
}
}
}
}
Not sure if this is what you meant but if for factorial of N you want to have the sum of all factorials up to that value this is how you do it.
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)));
}
}
}
}
You need to add a total variable to keep track of the sum.
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);
}
short of totally understanding what you want to do exactly, here's two things...
- in programming, the following expression is perfectly valid:
i = i + 1
Saying "the new value of i is the old value of i plus one" - variables live within scopes, their boundaries usually being braces
{ }
, that is you will need a variable that is outside the braces of the foreach in order to "remember" stuff of the previous iteration.
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)));
}
}
精彩评论