C - 将数字添加到列表中?(就像python)

C++ - Adding numbers to a list? (like Python)

本文关键字:就像 python 列表 数字 添加      更新时间:2023-10-16

我是编程的新手,但是正在尝试同时学习python和c (一个与工作有关,另一个是业余时间(。我在C 中使用以下代码进行停车传感器进行测量:

> for (i=0; i<20; i++) {
>     digitalWrite(TRIG1, LOW);
>     delay(2);
>     digitalWrite(TRIG1, HIGH);
>     delay(10);
>     digitalWrite(TRIG1, LOW);
>     d = pulseIn(ECHO1, HIGH);
>     d = d/58;
>     delay(13);
>     }

这应该测量距离并将其存储在d中。它将在500毫秒的时间内完成20次。我现在想存储这20个测量值中的每一个,并从中获得中值。

在Python中,我可以创建一个列表,然后将数字添加到其中。C 中有什么等效的吗?如果没有,建议其他哪些方法在不编写非常长的代码的情况下进行中位数?

如果您必须使用普通C( (使用整数值数组:

int d[20];
for(int i = 0; i < 20; ++i)
  d[i] = measureValue();

如果可以使用STL(标准模板库(,请使用std :: vector:

#include <vector>
std::vector<int> d;
for(int i = 0; i < 20; ++i)
  d.push_back(measureValue());

如果您正在为Arduino写作,则可能需要为Arduino安装标准C (请参阅https://github.com/maniacbug/standardcplusplus/standardcplusplus/blob/master/master/master/readme.md.md(

相关文章: