Problems with code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Problems with code

I create a program that calculates the products of a series of numbers."k" we type from the keyboard.I also do not understand how to find factorial in my incident.Help me please with the implementation My code #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int n,k; float z,prd=1; printf("Enter k: \n"); scanf("%d",&k); for(n=-3;n<=k;n++) { z=((n+2)*(abs(n-4))/(n+3); // (n+3)!(factorial) prd*=z //product of numbers } printf("5.2f \n",prd); return 0; }

12th Nov 2018, 10:21 AM
Alex
Alex  - avatar
6 Answers
+ 3
Alright. That product is 0 as soon as n is -2. But still, to calculate the factorial you can either write a simple algorithm yourself. Can look like this: int factorial(int n) { int f = 1; while(n) f *= n--; return f; } But that means to repeat a lot of computations. It'd be smarter to produce the factorial as a side-effect of the loop. A thing to remember: When dividing integers it will be integer division (division with remainder). To get floating points, you first need to convert one element to a floating point type (explicit type cast). So, the loop could look like this: double prod = 1.0; int f = 1; for(int n=-3; n<=k; n++) { prod *= ((double)(n+2) * abs(n-4)) / f; f *= n+4; } Edit: Just in case the product is supposed to be a sum (which would make more sense to me...): double z = 0; int f = 1; for(int k=-3; k<n; k++) { z += ((double)(k+2) * abs(k-4)) / f; f *= k+4; }
12th Nov 2018, 1:42 PM
Leif
Leif - avatar
+ 2
Could you write out the series you want to calculate without using "code" ? Right now, as soon as n is -2 one factor becomes zero. That means your product will become zero. [I understand that the denominator is supposed to be factorial, right? Otherwise you run into trouble there as well, dividing by 0...]
12th Nov 2018, 12:46 PM
Leif
Leif - avatar
+ 2
I am sorry, that makes even less sense than before. Now, you are trying to take the factorial of a negative number which isn't defined. The k-th term is (k+2) |k-4| / (k-4)! or (k+2) |k-4| / (k+3)! ? And the product runs from k=-3 up to n ?
12th Nov 2018, 1:25 PM
Leif
Leif - avatar
+ 1
thank you,Leif!
12th Nov 2018, 2:09 PM
Alex
Alex  - avatar
0
z=П k up,n=-3 down below (n+2)|n-4|/(n-4)!
12th Nov 2018, 1:06 PM
Alex
Alex  - avatar