【问题标题】:C++ functions with pointers带指针的 C++ 函数
【发布时间】:2020-12-14 07:59:36
【问题描述】:

什么是错误?如何解决?此代码是使用指针和函数查找圆的区域。我面临的错误是&answer 无法转换为浮点数。

#include <iostream>

using namespace std;

void area(float, float);

int main()
{
    float radius, answer = 0.0;
    cout << "Enter a radius:";  // Take the radius from the user.
    cin  >> radius;
    area(&radius, &answer);
    cout << "Area of circle is:" << answer;
    return 0;

}

void area(float *value, float *result)  // This is the function to calculate the area.
{
    *result = 3.142 * (*value) * (*value);
}

【问题讨论】:

  • void area(float,float); 你的原型没有指针。
  • 这是c++11 还是c++14?不能同时使用两者,因此请编辑您的问题以包含您正在使用的问题。
  • @TrebledJ 是正确的,您应该更改前向减速,因为它与函数不匹配。
  • 不要以这种方式使用指针。整个函数应该只是float area(float value) { return 3.142f * value * value; }

标签: c++ c++11 c++14


【解决方案1】:

您可以做以下两件事之一:

  • 将原型改为void area(float*, float*);
  • 移除原型并移动函数:
    void area(float *value, float *result)  // This is the function to calculate the area.
    {
        *result = 3.142 * (*value) * (*value);
    }
    

main() 函数之上。这两种方法都可以。

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2018-01-03
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
  • 2015-09-03
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
相关资源
最近更新 更多