【问题标题】:I keep getting the error "cannot convert 'float*' to 'float' in return"我不断收到错误“无法将 'float*' 转换为 'float' 作为回报”
【发布时间】:2019-11-12 01:11:11
【问题描述】:

我是 C++ 新手,我正在使用 Arduino 平台。我正在为我的项目编写一个程序,有一次我需要将笛卡尔坐标系转换为圆柱坐标系。该程序接收一个大小为 3 的浮点数组并对其进行一些处理,然后返回一个大小为 3 的新浮点数组,其中包含另一个系统中的坐标。我不断收到错误“退出状态 1,无法将 'float*' 转换为 'float' 作为回报”,我完全不知道我的代码有什么问题或如何修复它。有人可以帮我了解发生了什么吗?

float CartesianToCylindrical (float pos[]){          //pos is in the form of [x,y,z]//
 float cylpos[3];
 cylpos[0] = sqrt((pos[0] ^ 2) + (pos[1] ^ 2));
 cylpos[1] = atan(pos[1] / pos[0]);
 cylpos[2] = pos[2];
 return cylpos;                                      //return in the form of [r,theta,z]//

【问题讨论】:

  • 你不能返回一个数组。
  • 你知道operator ^ 是异或吗?它对您的浮点数有效吗?
  • 顺便说一句,X * Xpow(X, 2) 更有效。
  • 记得检查pos[0] 是否有0

标签: c++ arrays function arduino


【解决方案1】:

不幸的是,C 风格的数组不是 C++ 中的一流对象,这意味着您不能像处理其他对象类型一样轻松地从函数中返回它们。有一些方法可以绕过这个限制,但它们很尴尬。 C++ 的最佳方法是定义一个对象类型,如下所示:

#include <math.h>
#include <array>
#include <iostream>

// Let's define "Point3D" to be an array of 3 floating-point values
typedef std::array<float, 3> Point3D;

Point3D CartesianToCylindrical (const Point3D & pos)
{
   //pos is in the form of [x,y,z]//
   Point3D cylpos;
   cylpos[0] = sqrt((pos[0] * pos[0]) + (pos[1] * pos[1]));
   cylpos[1] = atan(pos[1] / pos[0]);
   cylpos[2] = pos[2];
   return cylpos;
}

int main(int, char **)
{
   const Point3D p = {1,2,3};
   const Point3D cp = CartesianToCylindrical(p);
   std::cout << "(x,y,z) = " << cp[0] << ", " << cp[1] << ", " << cp[2] << std::endl;
}

....这样您就可以自然地传递和返回您的点值。

【讨论】:

  • 也许不是,但我的回答与数学无关;它是关于如何传递/返回 3D 点值的。
  • 我会推荐更现代的using Point3D = std::array&lt;float, 3&gt;; ,而不是typedef
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多