当编译器从float转换为双奇怪的行为 [英] Strange behavior when compiler converts from float to double

查看:129
本文介绍了当编译器从float转换为双奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

float foo[3];

在鲍文件我要送他们一到PID作为输入。

In the ino file I have to send one of them to the PID as input.

double output;
PID myPID(&input, &output, &target, 1, 0.0, 1.1, DIRECT);
...
void loop(){
  input =foo[2];   
  myPID.Compute();
  Serial.print(output); //output: "nan"
...
}

PID是如下:

The PID is as follow:

PID::PID(double* Input, double* Output, double* Setpoint,
        double Kp, double Ki, double Kd, int ControllerDirection)

它编译但PID outvalue的输出为南。

It compiles but the output of the PID outvalue is nan.

但是,如果我的输入设置为-1.2,然后它的作品。

However if I set the input to -1.2 then it works.

void loop(){
      input =foo[2];  
      input = -1.2;
      myPID.Compute();
      Serial.print(output); //output: "1200"
    ...
    }

我该如何解决这个问题?编译器应该自动转换双浮动。正如兆2560。
我也曾尝试:输入=双(富[2]); 没有任何成功

编辑:

  Serial.print(foo[2]);  //Prints -9.2
  foo[2] = -9.2;         // I manually set foo[2] to -9.2  
  xAngle = foo[2];
  xPID.Compute();        //Computes perfectly.

我要补充一点,foo是一个自定义库。这太奇怪了。任何人都得到了这个线索?

I have to add that foo is in a custom library. This is so strange. Anyone got a clue about this?

推荐答案


  • 首先,所有的AVR双打花车为这里或描述的此处。这使得双打是一样的Arduino的巨型彩车2560可以通过对比验证这一点的sizeof(双); 的sizeof(浮动); 都返回 4

  • 其次,如果你想投一种类型到另一种语法是(TARGETTYPE)sourceType的,所以如果你做那种事情,你的任务应该是这样的。

  • First of all, all AVR doubles are floats as described here or here. This makes doubles be the same as floats on Arduino Mega 2560. You can verify this by comparing sizeof(double); and sizeof(float); both will return 4.
  • Secondly, if you want to cast one type to another the syntax is (targetType)sourceType, so if you do that sort of a thing, your assignment should look like this

    input =(double)foo[2];
    


  •     input =(double)(foo[2]);
    

    然而,这是在这种情况下不相关,因为双和浮标是相同的。

    However, this is irrelevant in this case since doubles and floats are identical.

    我觉得最有可能的问题来自于一个事实,即PID控制器不喜欢你在的任何值富[2] 给你设置的参数。您是否尝试过 foo的[2] = - 1.2 分配之前输入= foo的[2];

    I think most likely the problem comes from the fact that your PID controller does not like whatever value you have in foo[2] given the parameters you set. Have you tried foo[2]=-1.2 before assigning input = foo[2];?

    这篇关于当编译器从float转换为双奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆