I was assigned a Hw that required me to calculate the value of e via using the series:
1 + 1/1! + 1/2! + ...1/n!
The value of e must be calculated until the value of n (entered by the user) is reached. Also, the value of 1/n! must be calculated until it's value is smaller than epsilon (also entered by the user).
I wrote the code, but there are some errors that compiler is telling me errors such as relational comparisons, use of ';' etc. Could anyone please help me fix the error. Thank you in advance.
Below is my code:
#include<stdio.h>
int factorial (int i)
{
if (i==0)
return 1;
else
return i*factorial(i-1);
}
int main(void) {
int i,n;
float e,ep;
printf("what is the value of epsilon: ");
scanf("%f",&ep);
printf("what is the value of n: ");
scanf("%d",&n);
for (i=1; i<=n, i++)
e= 1+1/factorial(i);
for(1/fatorial(i)<=ep)
printf("The value of e for the entered value of epsilon and n:%f",e);
return 0;
}
For more precision I would use double instead of float.
for (i=1; i<=n, i++)
e= 1+1/factorial(i);
This is wrong, you are not adding to e, you are assigning always the last
value of the series, which is always 0 (except for i = 1). So your e will
always be 1.
factorial is a function that returns an int. A int divided by an int is
an int and in C anything 1/x (for x > 1, x integer) is 0. You you to use
1.0 or cast at least one of the arguments to double (or float if you are
using floats):
double e = 1; // initializing e
for(i = 1; i <= n; ++i)
e += 1.0/factorial(i);
Also, the value of 1/n! must be calculated until it's value is smaller than epsilon, also entered by the user.
I don't understand what that means, if n is a fixed value given by the user,
what do you keep calculating? Is this really what the exercise says?
My interpretation would be: if by n steps |e_real - e_calculated| > epsilon,
keep incrementing n, otherwise stop. That would be
#include <stdio.h>
#include <math.h>
#include <stdint.h>
uint64_t factorial (uint64_t i)
{
if (i==0)
return 1;
else
return i*factorial(i-1);
}
int main(void)
{
int n;
double e = 1;
double epsilon;
printf("what is the value of epsilon: ");
scanf("%lf", &epsilon);
printf("what is the value of n: ");
scanf("%d",&n);
int i = 1;
while(1)
{
e += 1.0/factorial(i++);
if(i >= n && (fabs(e - M_E) < epsilon))
break;
}
printf("e: %.20lf, calculated e: %.20lf, error: %.20lf, steps: %d\n", M_E, e, fabs(e-M_E), i);
return 0;
}
Note: if you are using GCC, you have to compile it with the -lm option:
$ gcc e.c -oe -lm
You're not summing the series but actually set e to 1.
Because you set it to e + 1/factorial(n) but your factorial() returns an int which is very likely to be above 1, so the division is integral, and 1 divided by any greater number will give 0.
The last loop is very strange. Did you mean while rather than for? Note that factorial is mistyped. Moreover, no work is done in the loop's body other than printing the same message over and over.
Related
C program for first seven terms in natural logarithm. I am not getting the right answer, can anyone review the following code.
#include<stdio.h>
int main(){
float x,i,sum,result=0;
printf("Enter value of x:");
scanf("%f",&x);
for(i=2;i<=7;i++)
{
sum = (x - 1)/x;
result = (sum + (0.5 * pow(sum,i)));
}
printf("Sum of series of Natural Logarithm is: %0.2f",result);
return 0;
}
You haven't implemented the series correctly.
The iteration should begin at 1
The 0.5 is only correct for the second term
You overwrite result from each term instead of summing it.
Here is the corrected code. I also changed float to double, and i to int.
#include <stdio.h>
#include <math.h>
int main(void)
{
double x, sum, result = 0;
int i;
printf("Enter value of x: ");
int res = scanf("%lf", &x);
if(res != 1 || x <= 0.5) // validate
return 1;
for(i = 1; i <= 7; i++)
{
sum = (x - 1) / x;
result = result + pow(sum,i) / i;
}
printf("Sum of series of Natural Logarithm is: %f\n", result);
printf("The library function log() calculates: %f\n", log(x));
return 0;
}
Program session
Enter value of x: 0.75
Sum of series of Natural Logarithm is: -0.287697
The library function log() calculates: -0.287682
Hello im new to C programming and this is my C Quiz question.
I tried really hard but i cant find the solution or whats wrong with my code.
This equation block cant work.
Any help will be appreciated
Write a C program that displays the below menu and performs the
corresponding operation, according to the selected menu item.
Write separate functions for each menu item and call the related function according to the
selection.
The menu:
(1) Calculate fibonacci value of the entered number,
(2) Calculate the equation (Get value of R from the user),
(3) Get four numbers from the user, sort them in ascending order
Enter your choice:
When the user enters a number (1, 2 or 3) corresponding function will be called
to perform the operation.
The user will enter -1 if he wants to continue and the
menu will be appeared on the screen again.
Question Equation Pic
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int numForFibonacci)
{
int i = 0;
int j = 1;
int k = 1;
for (int b = 1; b <= numForFibonacci; b++)
{
k = i + j;
printf("%d \n", i);
i = j;
j = k;
printf("%d ", k);
}
printf("\n");
return k;
}
float theEquation(float numR)
{
float multipl, result = 1;
for (int i = 1; i <= numR; i++)
{
multipl = (2i + 4) / (i * i);
result *= multipl;
}
printf("Result is %f", result);
return result;
}
int ascending(int n)
{
int k = 0, i = 0, j = 0, number[4];
for (int w = 0; w < n; w++)
scanf("%d", &number[w]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
k = number[i];
number[i] = number[j];
number[j] = k;
}
}
}
for (i = 0; i < n; ++i)
printf("\n%d \n", number[i]);
return i;
}
int main()
{
int choice, choiceFibo;
float choiceR;
do
{
printf("[1]Fibonacci calculation\n");
printf("[2]calculating the equation: (2k+4)/(k*k)\n");
printf("[3]sorting numbers in ascending order\n");
scanf("%d", &choice);
if (choice == 1)
{
printf("enter a number for fibonacci\n ");
scanf("%d", &choiceFibo);
fibonacci(choiceFibo);
}
else if (choice == 2)
{
printf("[2]enter a number for (2k+4)/(k*k)\n");
scanf("%f", &choiceR);
theEquation(choiceR);
}
else
{
printf("[3]enter four numbers to sort them in ascending order\n");
ascending(4);
}
printf("If you want to do another calculation enter '-1'.\n");
scanf("%d", &choice);
} while (choice == -1);
return 0;
}
TL;DR: Two main issues:
<integer>i in GNU C represents a complex number, not multiplication.
integer division is not what you'd expect
Your issue lies on this line:
multipl = (2i + 4) / (i * i);
You might think that 2i would evaulate as 2 * i, but in C, 2i is a complex int.
This can be seen here:
#include <stdio.h>
int main()
{
int i=1;
printf("%d", 2i);
return 0;
}
You would expect this to print 2, but instead we get a warning.
Compiled with onlinegdb:
warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘complex int’
Second issue: Integer division. The other answer already covered it pretty well, but for the sake of self-contained answers:
In C, integer division finds the integer solution and discards the remainder.
2/5 = 0
6/5 = 1
10/5 = 2
10/4 = 2
10.0 / 4 = 2.5
(double)10/4 = 2.5
You need to "type coerce" one of the values in your numerator or denominator to a float/double, which will coerce the entire fraction to a float/double.
You can do this either with 2.0*i or (double)2*i. Either one works, but the second one is more explicit for readability.
To fix the issue, simply change 2i to (double)2*i.
There are only three edits required to get a clean compile:
Change int main() to int main(void)
Change (2i + 4) / (i * i) to (2*i + 4) / (i * i)
Change int ... number[4]; to int ... number[4]={0};
If you did not see something similar to the following upon your compile, then turn on all warnings:
> s0_15.c - 4 warnings
> 28, 28 warning: implicit conversion discards imaginary component: '_Complex int' to 'float'
> 45, 17 warning: variable 'number[i]' may be uninitialized when used here
> 38, 5 note: variable 'number' is declared here
> 54, 27 warning: variable 'number[i]' may be uninitialized when used here
> 38, 5 note: variable 'number' is declared here
> 58, 5 warning: function declaration isn't a prototype.
To ensure accurate calculations, see integer division addressed in another answer under your post.
Help me to find the sum of this series x^1+x^4+x^7+.. to n terms
#include<conio.h>
#include<math.h>
int main(int argc, char const *argv[]) {
int n;
float x;
int l=1;
printf(" Enter the value of x :");
scanf("%f",&x);
for (int i = 1; i <=n; i++)
{
l = pow(x,l+3);
}
printf("x ^ %d + power %d",x,l);
return 0;
}
I think this is what you want :) i've commented the errors
#include<conio.h>
#include<math.h>
int main(int argc, char const *argv[]) {
int n;
float x;
float l=0,i=0;
// initialize n first to determine how far the sum should go
printf(" Enter the value of n :");
scanf("%d",&n);
printf(" Enter the value of x :");
scanf("%f",&x);
for (int i = 0; i <n; i++)
{ //l+= pow(x,(i*3)+1); is equivilant to l= l+ pow(x,i+3); which i assume that's what you wanted to do
// l should be a float as well not int since x is a float
l+= pow(x,(i*3)+1);
if(i!=n-1)printf(" %f^%d +",x,i*3+1);
else printf("%f^%d",x,i*3+1);
}
printf("\nResult of the sum is %f",l);
return 0;
}
There's a problem in this loop:
for (int i = 1; i <=n; i++)
{
l = pow(x,l+3);
}
You set l every time and then in the end it has the value of the last assignment, but you wanted to add them all up. Also, it should be i in the pow call, not l+3, instead you should move that step of 3 to the loop increment. Try this:
int l = 0;
for (int i = 1; i <= n; i+=3)
{
l += pow(x, i);
}
Also make sure that you initialize n, you should probably read it in using scanf, just like you do with x.
Also note that since l is int, it's going to be truncated every time. If you don't want that, you should declare it as float instead, and depending on how precise the result should be, you might even want to consider double.
#include <stdio.h>
#include <math.h>
int main()
{
double x;
unsigned n;
fprintf(stderr, "enter x and n :");
/* enter x as a double and x as an unsigned number, both on the same line, and check 2 values are enter */
if (scanf("%lg %u", &x, &n) != 2)
puts("invalid or missing values");
else {
double r = 0; /* sum initialization */
int p = 1; /* the power to apply, 1 then 4 then 7 etc */
while (n--) { /* have to sum n times */
r += pow(x, p); /* x^1+x^4+x^7+... */
p += 3; /* next power value */
}
printf("%g\n", r);
}
return 0;
}
if I well understand n terms x^y must be added rather than the last pow is x^n, I use double for x and of course the result ( r )
Executions :
enter x and n :1.2 3
6.85678
enter x and n :2 1
2
Check with bc :
% bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
scale=6
1.2 + 1.2^4 + 1.2^7
6.856780
Multiple operations on floating point numbers tend to compound rounding errors very quickly, so if you can minimize the number of operations, always do.
Now if you recognize that your polynomial is a Geometric series (see wikipedia article) with a = x and r = x^3, then we have the following pseudo-code algorithm (note no loops!):
Case 1 (x == 0): Sum == 0 regardless of n.
Case 2 (x == 1): Sum == n.
Case 3 (x any other number): Sum == x*(1-(x^(3*n)))/(1-(x^3)).
Case 4 (n==infinity and -1<x<1): Sum == x/(1-(x^3)).
I trust you can code accordingly.
I have another problem for homework. This time I know where I am at generally, but I can see that I have some glaring issues with the code. Recently I lost my keys, and it's kind of like that. I don't know exactly WHERE I went wrong with my code, but I have a good idea, and I'd like you to help me find it.
The problem is to approximate pi using the Taylor series.
Now, my problem isn't exactly to get it to approxate so that it equals pi. Rather approximate pi using first N terms as entered by the user. So for example, if I would enter 2, then I should run through the first 2 since N=2. My problem is the way printF represents it (and a variable appears to be uninitialized). Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
//program to calculate series of numbers equal to pi/4
//declare variables
int num_Terms;
int sign= 1;
int n;
float sum= 0.0;
float next_Term;
float final_sum;
//prompt user for input
printf("Enter a value for integer n: ");
scanf("%i",&n);
//perform calculations
for(n = 1; n<= num_Terms; n=n+1) {
sum= sum+next_Term;
next_Term = sign*(1.0/(2*n-1));
sign = sign*-1;
}
final_sum = sum*4;
//display result
printf("\n 4 * %f = %f\n",sum, final_sum);
return 0;
}
I don't know exactly WHERE I went wrong with my code
Firstly you are scanning value into a variable n and then later using it as an iterator variable. Change this to be num_Terms. This should solve your main problem of not considering the number of terms.
Then, it is preferable to initialize the variable before you use it, which would then get rid of the warning you get.
int main(void)
{
//program to calculate series of numbers equal to pi/4
//declare variables
int num_Terms = 0;
int sign = 1;
int n = 0;
float sum = 0;
float next_Term = 0;
float final_sum = 0;
//prompt user for input
printf("Enter a value for integer n: ");
scanf("%i",&num_Terms);
//perform calculations
for(n = 1; n<= num_Terms; n=n+1) {
//not too sure if you need to reverse this order of calculation of sum
sum = sum + next_Term;
next_Term = sign * (1.0/(2*n-1));
sign = sign * -1;
}
final_sum = sum * 4;
//display result
printf("\n 4 * %f = %f\n",sum, final_sum);
return 0;
}
i am doing one of the simple programin C, sum of digits of 5 digit number.Though i had done it using a simple function but i need to do it with recursion also.I had read many solution on net regarding this problem using recursion and had implemented one of mine.But that is giving error and i cant figure out what mesh i am doing in my algo.
#include<stdio.h>
int sum5(int x); //function for sum of digits of 5 digit number
int main()
{
int x;
int result;
printf("Enter a 5 digit number : ");
scanf("%d",&x);
printf("Number entered by you is %d",x);
result = sum5(x);
printf("Sum of digits of 5 digit number is = %d",&result);
return 0;
}
int sum5(int x)
{
int r;
int sum=0;
if(x!=0){
r=x%10;
sum=sum+r;
x=x-r; //doing this so that 0 come in the last and on diving it by 10, one digit will be removed.
sum5(x/10);
}
return sum;
}
but after its execution i am getting wrong result.It is dumping some anonymous value on the output.
Also, your sum5 function is incorrect. You have to add the value of sum5 to the sum variable of the caller function.
int sum5(int x)
{
int r;
int sum = 0;
if (x != 0) {
r = x % 10;
sum = r;
//x = x - r; - this isn't required. integer division will floor x
sum += sum5(x / 10);
}
return sum;
}
This is incorrect as it is printing the address of result and not its value:
printf("Sum of digits of 5 digit number is = %d",&result);
Change to:
printf("Sum of digits of 5 digit number is = %d", result);
Always check the result of scanf() to ensure a valid value was read:
/* Returns number of assignments made. */
if (scanf("%d", &x) == 1 && x > 9999 && x < 100000)
{
}
Plus the error in the implementation of sum5() as pointed out by Osiris
.