<c ++>构造代码输出</c ++>

时间:2013-04-04 02:01:15

标签: c++ struct constants output void

#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>

using namespace std;


struct sphere_t  { float radius; }; sphere_t sph = { 5.8 };

void SphereDescription(sphere_t &sph) {     cout << "Sphere's
description: "; cin >> 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; }

//the volume and surface area of cylinder 

struct cylinder_t { float
radius ; float height ; }; cylinder_t cylr,cylh = { 6.6,1.3 };


double SurfaceAreaCylinder(const cylinder_t &cylr,const cylinder_t&cylh)
{   return (2*M_PI*cylr.radius)*2 +2*M_PI*cylr.radius*cylh.height; }

double CylinderVolume(const cylinder_t &cylr,const cylinder_t &cylh) {  return 2*M_PI*cylr.radius*cylr.radius*cylh.height; }


int main() { cout << "Sphere's description radius: " << sph.radius << endl; cout << "Surface Area: " << SphereSurfaceArea(sph) << endl; cout << "Volume :" << SphereVolume(sph) << endl;

cout << "Cylinder's description radius: " << cylr.radius << endl; cout << "Cylinder's description height: " << cylh.height << endl; cout << "Surface Area: " << SurfaceAreaCylinder(cylr,cylh) << endl; cout << "Volume :" << CylinderVolume(cylr,cylh) << endl;

system("pause");   return(0); }

//输出

Sphere's description radius: 5.8

Surface Area: 422.733

Volume : 817.283

Cylinder's description radius: 0

Cylinder's description height: 1.3

Surface Area: 0 

Volume : 0

为什么半径,SA和音量输出为零?

2 个答案:

答案 0 :(得分:1)

cylr未初始化,仅为cylh

cylinder_t cylr,cylh = { 6.6,1.3 };

请改为尝试:

cylinder_t cylr = { 1.1, 2.2 }, cylh = { 6.6,1.3 };

答案 1 :(得分:0)

您的代码存在以下问题:     struct cylinder_t {        浮动半径;        浮高;     };     cylinder_t cylr,cylh = {6.6,1.3};

这里你要声明两个结构变量(你打算做什么?) 只有cylh初始化为值(6.6,1.3),cylr未初始化

所以,cylh.height返回1.3(因为它用它初始化),但是cylr.radius返回0,因为它未初始化。这个问题导致其他值为0