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

 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操作。 所以我怎么显示结果?

===============>>#1 票数: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";
}

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

===============>>#2 票数: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);

===============>>#3 票数:-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;
}

  ask by user1092492 translate from so

未解决问题?本站智能推荐:

关注微信公众号