C language programming (third edition) He Qinming exercises 4-2

C language programming (third edition) He Qinming exercises 4-2

List of exercises
1. C language programming (third edition) He Qinming exercises 2-1
2. C language programming (third edition) He Qinming exercises 2-2
3. C language programming (third edition) He Qinming exercises 2-3
4. C language programming (third edition) He Qinming exercises 2-4
5. C language programming (third edition) He Qinming exercises 2-5
6. C language programming (third edition) He Qinming exercises 2-6
7. C language programming (third edition) He Qinming exercises 3-1
8. C language programming (third edition) He Qinming exercises 3-2
9. C language programming (third edition) He Qinming exercises 3-3
10. C language programming (third edition) He Qinming exercises 3-4
11. C language programming (third edition) He Qinming exercises 3-5
12. C language programming (third edition) He Qinming exercises 4-1


topic

Expansion summation.
Input a real number x,
calculate and output the sum of the following formula,
until the absolute value of the last term is less than 0.000 01, the calculation result retains 2 decimal places.
It is required to define and call the function fact(n) to calculate the factorial of n, and you can call the pow() function to exponentiate.
Try to write the corresponding program.
Insert picture description here


Analysis process

enter

Condition: Enter a real number x

Output

Condition: Calculate and output the sum of the following formulas
until the absolute value of the last item is less than 0.000 01, and the calculation result retains 2 decimal places.

Code

#include <stdio.h>
#include <math.h>
double fact(int n);/*声明函数,计算阶乘*/

int main () {
    
    
	/*定义变量*/
	double x;                                                               /*定义变量,存储输入的x*/
	double m;                                                               /*定义变量,计算每一项值*/
	double sum = 1.0;                                                       /*定义变量,计算结果和,初值为1*/
	/*赋值*/
	printf("请输入x:\n");                                                  	/*输入提示*/
	scanf("%lf \n", &x);                                                    /*输入并赋给变量*/
    /*计算*/
    for(int i=1 ; ; i++){
    
    /*直到最后一项的绝对值小于0.000 01结束计算,即每项绝对值必须大于0.000 01*/
        m = pow(x, i)/ fact(i);
        sum = sum + m;
        if(fabs(m)< 0.00001) break;

    }
    
    printf("%lf和为:%.4lf \n", x, sum);                               		/*输出计算结果*/
	return 0;
}

double fact(int n){
    
    
    double sum=1.0;                                                         /*定义变量,存储阶乘和*/
    for(int i=1;i<=n;i++){
    
                                                      /*循环遍历,将每个元素乘到sum上*/
        sum *=i;
    }
    return sum;
}

operation result

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43228814/article/details/112345296