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

这里主要是讲解一下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:

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容