美文网首页我爱编程
ElecFun--Arduino-使用Arduino写一个数列求

ElecFun--Arduino-使用Arduino写一个数列求

作者: wayen_gogogo | 来源:发表于2015-12-27 21:44 被阅读370次

    这里主要是讲解一下Arduino的程序,使用了Arduino的编程语言,然后简单的写了一个求和函数,如果你对数学的等差数列还不太了解的话,可以点击查看相关的内容了解什么是等差数列的定义及其求和公式!

    这里利用了Arduino芯片作为一个处理器,然后跑一个程序,求出给定的一个数列,并求出这个等差数列的前n项和!下面是总程序得截图,如果你刚开始看不懂的话,没关系,后面我会逐行讲解其中的意思,以及这个程序还可以做怎样的改进!

    /* Arduino Arithmetic progression

    * this sketch demonstrate how to use Arduino to calculate a arithmetic progression

    *  2015/12/27

    */

    int summation_traverse(int beginNumber, int n , int d) 

    // 第一种方法求和,其实也就是利用了遍历的方法来求和的

    // 其中beginNumber 是数列的第一个项,n是要求和的前n项,

    // d就是数列的公差

    {

    int temp = beginNumber;

    int sum = 0;

    for (int i = 0; i < n; i++) // 下面就是对前n项进行求和了

    {

    sum = temp + sum; //每一次把一个数加起来,

    //直到把所有的项都加完为止

    temp = temp + d;//这个是第i个项

    }

    return sum;//然后把前n项和返回

    }

    int summation_arithmetic(int beginNumber, int n, int d) // second method , here use an formula calculate the sum

    {

    int sum = beginNumber * n + (n * (n - 1) * d) / 2; 

    // it is the formula of sum

    return sum;

    }

    void setup() {

    // put your setup code here, to run once:

    Serial.begin(9600);

    Serial.print("input a beginNumber and the n and the grade number d");

    Serial.println("As an example if you input beginNumber is 10, and the n is 15, the grade number is 4");

    Serial.print("the Sum result useing the summation_travse is:");

    Serial.println(summation_traverse(10, 15, 4));

    Serial.print("the sum result using the summation_arithmtic is:");

    Serial.println(summation_arithmetic(10, 15, 4));

    }

    void loop() {

    // put your main code here, to run repeatedly:

    }

    相关文章

      网友评论

        本文标题:ElecFun--Arduino-使用Arduino写一个数列求

        本文链接:https://www.haomeiwen.com/subject/ngpbhttx.html