#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
using namespace std;
//the volume and surface area of sphere
struct sphere_t { float radius; };
sphere_t sph;
sph.radius = 3; // this is the part that mess me up, error in sph.radius
double SphereSurfaceArea(const sphere_t &sph)
{
return 4*M_PI*sph.radius*sph.radius;
}
double SphereVolume(const sphere_t &sph)
{
return 4.0/3.0*M_PI*sph.radius*sph.radius*sph.radius;
}
int main()
{
cout << "Sphere's description: " << sph.radius << endl;
cout << "Surface Area: " << SphereSurfaceArea(sph) << endl;
cout << "Volume :" <<SphereVolume(sph) << endl;
system("pause");
return(0);
}
我得到的输出是:
实体的描述表面积体积
如何通过常量引用将数字放在const函数中并将函数设置为void而不返回任何内容?
答案 0 :(得分:2)
您可以将初始化与全局变量的定义结合在一行:
sphere_t sph = { 3 };
答案 1 :(得分:2)
此
sph.radius = 3;
是赋值语句,它将值3赋给sph.radius。 C ++规则是赋值语句只能在函数中使用。你已经在函数之外写了一个。
我会写这样的代码
int main()
{
sphere_t sph;
sph.radius = 3;
cout << "Sphere's description: " << sph.radius << endl;
cout << "Surface Area: " << SphereSurfaceArea(sph) << endl;
cout << "Volume :" << SphereVolume(sph) << endl;
system("pause");
return(0);
}
现在赋值(和sph的声明)在函数main中。