错误C2065:未声明的标识符

时间:2011-12-11 17:41:09

标签: c++

这是一个非常基本的问题,我需要找到一个球体的面积和体积,但我收到了这个错误:

 error C2065: 'v' : undeclared identifier
 error C2065: 'a' : undeclared identifier

这是我的计划:

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;
int r;
int computeSphere(int r) {
    double a,v;
    a = 4*3.14* pow(r,2);
    v = (4/3) * 3.14 * pow(r,3);

    return a,v;
}

int main() {
    cout << "Enter the radius: ";
    cin >> r;
    cout << fixed << setprecision(2);

    computeSphere(r);

    cout << "The area of a sphere of radius " << r << " is " << a << " and its ";
    cout << "volume is ";
    cout << v;
    cout << endl;

    return 0;
}

问题是该函数不应执行任何I / O操作。 那我怎么能显示结果?

3 个答案:

答案 0 :(得分:4)

两个问题:

  • 您无法从函数返回多个值。
  • 您没有对调用该函数的返回值执行任何操作。

解决第一个问题的一种方法是定义一个结构:

struct SphereStuff
{
    double a;
    double v;
};


SphereStuff computeSphere(double r)
{
    SphereStuff stuff;
    stuff.a = ...;
    stuff.v = ...;
    return stuff;
}

int main()
{
    SphereStuff s = computeSphere(42);        // ***
    std::cout << s.a << ", " << s.v << "\n";
}

另请注意我如何“收集”函数的返回值(在标有“***”的行上)。

答案 1 :(得分:0)

将其分为两个功能

double Volume (int r) { return (4/3) * 3.14 * pow(r,3); }
double Area (int r) { return 4*3.14* pow(r,2); }

然后像那样使用它

double v = Volume(r);
double a = Area(r);

答案 2 :(得分:-1)

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;
int r;

double calc_a(int r){
    return 4*3.14* pow(r,2);
}

double calc_v(int r){
    return (4/3) * 3.14 * pow(r,3);
}

int main()
{
  double a,v;  

  cout << "Enter the radius: ";
  cin >> r;

  a = calc_a(r);
  v = calc_v(r);

  cout << fixed << setprecision(2);    
  cout << "The area of a sphere of radius " << r << " is " << a << " and its ";
  cout << "volume is ";
  cout << v;
  cout << endl;

  return 0;
}