gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:02:49 25 4
gpt4 key购买 nike

我能够将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com