C language case score column summation -11

Title: There is a sequence of numbers: 2 / 1, 3 / 2, 5 / 3, 8 / 5, 13 / 8, 21 / 13 ... Find the sum of the first 20 items of this sequence.

program analysis

This is a typical mathematical logic problem of fraction series. To study this kind of problem, it is necessary to find their distribution law from known conditions.
We arrange the numerators and denominators of the first 6 recommendations, and carefully observe the regular
numerators: 2, 3 , 5, 8, 13, 21
Denominator: 1, 2, 3, 5, 8, 13
Whether observed from the numerator or the denominator, the denominator of the latter fraction is the numerator of the previous number, and the numerator of the latter number is the former Add the denominator to the numerator of a number.

Step 1: Define Program Goals

Write a C program to find 2 / 1, 3 / 2, 5 / 3, 8 / 5, 13 / 8, 21 / 13... Find the sum of the first 20 items of this sequence.

Step 2: Program Design

The whole program is divided into two modules. The first module is to use the for loop to traverse 20 items. The second module is to accumulate scores, define a sum variable, numerator variable a, denominator variable b, and each cycle variable is sum+= a/b, tmp=a, a+=b, b=tmp, and then output the result outside the loop.

Write code

#include<stdio.h>
int main(){
    
    
    float sum=0,a=2,b=1,tmp;
    for(int i=0;i<20;i++){
    
      //进行20次循环
        sum+=a/b;   //每次循环都累加分数
        //进行分子分母变换
        tmp=a;
        a=b+a;
        b=tmp;
    }
    printf("总数为%.3f\n",sum);   //输入累加后的总结果
    return 0;
}

Effect:
insert image description here

Summarize

Is this math problem more difficult than the previous ones? It is easy to understand the logic of its superposition, but converting program design into code implementation requires more personal logic ability! You must do more questions, practice makes perfect, the proportion of people with good mathematical talents is very low in the world. For more program case projects, please click the link to view the C language case of General Zod . Well, see you in the next chapter, come on!

Guess you like

Origin blog.csdn.net/weixin_37171673/article/details/132231242