无法在结构中创建 1 个球体实例

Can't Create 1 instances of sphere in structs

本文关键字:实例 创建 结构      更新时间:2023-10-16
#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不返回任何东西?

您可以将初始化与全局变量的定义合并为一行:

sphere_t sph = { 3 }; 

This

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中