c++ - 我不断收到错误 "cannot convert ' float *' to ' float' 作为返回”

标签 c++ arrays function arduino

我是 C++ 的新手,我正在使用 Arduino 平台。我正在为我的项目编写程序,有一次我需要将笛卡尔坐标系转换为圆柱坐标系。该程序接受一个大小为 3 的 float 组并对其执行一些操作,然后返回一个大小为 3 的新 float 组以及另一个系统中的坐标。我一直收到错误“退出状态 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]//

最佳答案

不幸的是,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;
}

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

关于c++ - 我不断收到错误 "cannot convert ' float *' to ' float' 作为返回”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58810642/

相关文章:

c++ - C++ Makefile错误 “implicit entry/start for main executable”

javascript - 如何将输入表单中的文本移动到 div

c++ - 同一函数的两个版本(用于内联或 constexpr)

c++ - 是否有围绕类添加方法的最薄包装器之类的东西?

java - 使用 LLVM 运行 javacpp 预设时出现 UnsatisfiedLinkError

c++ - 在 linux 下,如何通过 .html 运行应用程序

arrays - 数组转换问题

ios - 计算从当前位置到 x 个对象的距离,并使用从最近到最远的过滤器对它们进行排序

java - JButton 需要更改 JTextfield 文本

在循环中调用函数