c++ - 如何重复打印相同的值?

标签 c++ c arduino

我能够将 t 显示到屏幕上,但每次循环迭代时,t 的当前值都会在打印之前添加到先前的值。这意味着,它打印出 9,18,27,36...我该如何避免这种情况?我需要它在代码循环期间持续显示 9。

int d,i,p,s,t,arr[30];
float hp = 0;
float arr2[30];
void setup(){
  Serial.begin(9600);
}
void loop(){
    for (d = 0; d < 360; d++){
          if (sin(d*(PI/180))+1 + sin(d*(2*PI/180))+1> sin((d-1)*(PI/180))+1 
+ sin((d-1)*(2*PI/180))+1 && sin(d*(PI/180))+1 + sin(d*(2*PI/180))+1 > 
sin((d+1)*(PI/180))+1 + sin((d+1)*(2*PI/180))+1){
         arr2[i++] = sin(d*(PI/180))+1 + sin(d*(2*PI/180))+1;
        }
      }
for (p = 0;p <30; p++){
  if(arr2[p]!=0){
    if (arr2[p]>hp){
    hp = arr2[p];  
    }  
  } 
}
for (d = 0; d < 3600; d++){
      if (sin(d*(PI/180))+1 + sin(d*(2*PI/180))+1 >= hp){
         arr[s++] = d;
        }
      }
 for (s = 0; s < 30; s++){
  if (arr[s]!=0){
    t++;
   }
  } 
  Serial.println(t);
}

最佳答案

一般建议:

Define variables with the smallest scope possible. In your case, unless there is a reason to make t and d global variables, don't make them global variables. Make them function local variables.

将代码更改为:

void loop(){
   int t = 0;
   int d = 0;

   ...

   Serial.println(t);
}

这将解决您眼前的问题,更重要的是,您的代码将更加清晰。

关于c++ - 如何重复打印相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55214290/

相关文章:

c++ - 查找字母子串

c++ - 构造函数后面的宏。这是什么意思?

c++ - 有没有办法在c++中检测中文字符? (使用 boost )

创建 Windows API 以从命令行添加、修改、查询、删除注册表项

c - setlocale(LC_CTYPE, NULL) 可能返回哪些值?

c++ - arduino 上发生了奇怪的事情

arduino - ESP8266 上的链表出现 StoreProhibitedCause 异常

c++ - 为什么这不是 POD?

c - C 代码中的内存问题或 Arduino 限制?

c++ - 如何在 C++ 程序中运行 C 脚本代码