c++ - 为什么我不能在 if 循环中使用动态变量?

标签 c++ arduino

我正在尝试使用 (i),即正弦值的总和,作为我的 if 循环的基础。 if 循环需要将 (d) 的值存储到数组 arr 中,其中 sin(d*pi/180)+1 等于 (i) 的分数或倍数。当我尝试在 if 语句的右侧使用 i 时,代码无法正常运行,但如果我尝试使用常量,则代码可以运行。我需要一种使用变量的方法,因为我无法提前知道我将成为什么。

int arr[10];
//signed int d;
float i = 0;
int p;
float d;
float e;
//float s = sin(d*(PI/180))+1;//float produces decimals
void setup(){
  Serial.begin(9600);
}
void loop(){
  for(d = 0; d < 360; d++){
    i = i + sin(d*(PI/180))+1;//add each value to the previous one
  }
  Serial.println(i/360);//print the average of the values
    delay(500);  

  for(d = 0; d < 360; d++){
    if (sin(d*(PI/180))+1 == 1.5*i/360){
        arr[p++] = d;
      }
  }
  for(p = 0; p < 10; p++){
    Serial.println(arr[p]);
    delay(500);
  }

最佳答案

与我们在纸上做的不同,浮点值存储在内存中。 float 存储为 2 的幂。因此 0.5 或 0.25 可以精确存储,而 0.2 或 0.3 则不能。

您正在尝试比较两个 float (sin(d*(PI/180))+11.5*i/360d 在你的例子中(虽然它是 float )实际上表示为整数并被精确存储并且 i 是一个 float 。所以左右两侧可以大约相等但是真的很少(非常)相等。您可以使用这样的结构:

计数 fabs(arg1-arg2) 并将此结果与所需的 epsylon(表示参数之间无显着差异的一些次要值)进行比较。

关于c++ - 为什么我不能在 if 循环中使用动态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55135262/

相关文章:

audio - 使用arduino和声音传感器时串行监视器不断说0

c++ - 在 C++ 中连续流式传输多个文件

c - 错误: Expected unqualified-id before numeric constant

c++ - "Debug Assertion"数组、头文件和声明

python - Quantlib 1.14 和 Quantlib1.14-SWIG : versions of Visual C++ prior to VC++10 (2010) are no longer supported

c++ - C++ 上的预处理器重载

Eclipse 编译正确,但在 'Problems' View 中显示错误

javascript - 在网站上显示 DB 的值变化

c++ - const char 到 SQLCHAR 错误

C++ 获取我自己的 dll 的 CLSID