-3

I want to write this equation:

1+(2/n!)+(3/n!)+...+(n/n!),

But the result is always equal to 1. Where is the wrong code? My code:

Console.Write("Please Enter Your Number: ");

int num = int.Parse(Console.ReadLine());

int fact = 1;

for (int i = num; i > 1; i--)
{
    fact *= i;
}

Console.WriteLine("Fact= " + fact);

float result = 1;

for (int i = 2; i >= num; i++)
{
    result += (i / fact);

}
Console.WriteLine("Result= " + result);

Console.WriteLine("Press any key to exit...");

Console.ReadKey();
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
JOKO
  • 13
  • 1
  • 4
  • 1
    You use `(float) x` to cast `x` to a `float`. – Willem Van Onsem Oct 25 '17 at 17:29
  • 1
    Remember, in C# (and C and Java and several other languages): `int / int -> int`. That is, the *operands* determine the division operation mode. – user2864740 Oct 25 '17 at 17:30
  • The question isn't "how", it's *where*. And "where" is, "before you do any math with it that ought to be floating point math". – 15ee8f99-57ff-4f92-890c-b56153 Oct 25 '17 at 17:31
  • I test it but not correct! – JOKO Oct 25 '17 at 17:31
  • yes I made a mistake. – JOKO Oct 25 '17 at 17:44
  • Ignoring flat out non-working loop code standard [int to float](https://stackoverflow.com/questions/1042099/how-do-i-convert-int-decimal-to-float-in-c) provides the answer. Note that it is well known fact that [factorial is simply 0](https://stackoverflow.com/questions/13222207/why-computing-factorial-of-realtively-small-numbers-34-returns-0) - so you really should be getting "divide by zero" exceptions instead. – Alexei Levenkov Oct 25 '17 at 17:44
  • The reason is your condition in for loop in wrong. And there is some adjustment to make the result float. try this below code. for (int i = 2; i <= num; i++) { result += ((i * 1.0f)/ fact); } – Rakesh Burbure Oct 25 '17 at 17:46

1 Answers1

0

Because this does not loop

for (int i = 2; i >= num; i++)

If you had traced it out in debug it would have been obvious

<=

On the implicate cast this (i / fact) is probably performed before the cast so cast fact to float. (float)fact.

You don't have an int / decimal

You could use decimal rather than float

paparazzo
  • 44,497
  • 23
  • 105
  • 176