PTA 7-6 Find the sum of formulas [4] (15 points)

topic

Define the function main(), input a positive integer n, calculate and output the value of the following formula. It is required to call the function fact(n) to calculate n!, and the return value type of the function is double. ​​
Insert picture description here

Input format:

Input gives a positive integer n in one line.

Output format:

In one line, output the partial sum value S in the format of "sum = S", accurate to six digits after the decimal point, please note that there is a space on the left and right sides of the equal sign. The title guarantees that the calculation result does not exceed the double precision range.

Input sample:

3

Sample output:

sum = 0.958333

Code:

#include<stdio.h>
int main()
{
    
    
	double fact(int n);
	int x,i;
	double sum;
	scanf("%d",&x);
	for(i=1;i<=x;i++){
    
    
		sum+=i/fact(i+1);
	}
	printf("sum = %.6lf",sum);
	return 0;
}
double fact(int t)
{
    
    
	int j;
	double z=1;
	for(j=2;j<=t;j++){
    
    
		z*=j;
	}
	return z;
}


Guess you like

Origin blog.csdn.net/Anemia_/article/details/111601702