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

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

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


topic

Find the sum of the first n items in the interleaved sequence: input a positive integer n, calculate the sum of the first n items in the interleaved sequence, and
Insert picture description here
try to write the corresponding program.


Analysis process

enter

Condition: Enter a positive integer n

Output

Condition: output andInsert picture description here

Code

#include <stdio.h>
#include <math.h>

int main () {
    
    
	/*定义变量*/
	int n = 0;                                      /*定义变量,存储输入的正整数n*/
	int flag = 1;                                   /*每个元素正负,1代表正,-1代表负;第一个元素为正,所以flag默认值为1*/
	int denominator = 1;                            /*每个元素的分母值;第一个元素分母为1,所以denominator默认值为1*/
	double sum = 0;                                 /*存储计算总和*/
	/*赋值*/
	printf("请输入正整数n:\n");                    /*输入提示*/
	scanf("%d\n", &n);                              /*输入n整数并赋给变量*/
	/*计算数据和*/
	for(double i = 1 ; i<=n ; i++){
    
    
	    sum += flag * (i/denominator);              /*依次计算第i个元素值,加到sum上*/
        denominator += 2;                           /*第i个元素的分母值为前一个元素加2*/
	    flag = -flag;                               /*第i个元素的正负为前一个元素的flag的相反数*/
	}
	/*输出计算结果*/
	printf("前%d个数的总和为:%.6f \n", n, sum);/*输出提示*/
	return 0;
}

operation result

Insert picture description here

Guess you like

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