问题及代码:
/*
*Copyright (c)2015,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:score.cpp
*作 者:单昕昕
*完成日期:2015年3月14日
*版 本 号:v1.0
*
*问题描述:编写基于对象的程序,求3个长方柱(Bulk)的体积。数据成员包括长(length)、宽(width)、高(heigth)、体积,要求设计成员函数实现下面的功能:
(1)由键盘输入3个长方柱的长、宽、高;
(2)计算长方柱的体积(volume)和表面积(areas);
(3)输出这3个长方柱的体积和表面积。
*程序输入:3个长方柱的长、宽、高。
*程序输出:这3个长方柱的体积和表面积。
*/
#include <iostream>
#include <cmath>
using namespace std;
class Volume
{
public:
void setdata(double length,double width,double height);
double area();
double volume();
private:
double length;
double width;
double height;
};
//下面定义需要的成员函数
void Volume::setdata(double l,double w,double h)//赋值
{
length=l;
width=w;
height=h;
}
double Volume::area()//求面积
{
return 2*(length*width+width*height+height*length);
}
double Volume::volume()//求体积
{
return length*width*height;
}
int main()
{
int t=3,i=1;
while(t--)
{
double l,w,h;
cout<<"请输入长方柱"<<i<<"的长: ";
cin>>l;
cout<<"请输入长方柱"<<i<<"的宽: ";
cin>>w;
cout<<"请输入长方柱"<<i<<"的高: ";
cin>>h;
Volume v;
v.setdata(l,w,h);
cout<<"长方柱"<<i<<"的表面积为: "<<v.area()<<endl;
cout<<"长方柱"<<i<<"的体积为: "<<v.volume()<<endl;
i++;
}
return 0;
}
运行结果:
知识点总结:
类和对象的定义和使用。
学习心得:
写完了去看了贺老师的,觉得我自己的程序还是有很大局限性的。
代码如下:
#include <iostream>
using namespace std;
class Bulk
{
public:
void get_value();
void display();
private:
float lengh;
float width;
float height;
};
void Bulk::get_value()
{
cout<<"please input lengh, width,height:";
cin>>lengh;
cin>>width;
cin>>height;
}
void Bulk::display()
{
cout<<"The volume is: "<<lengh*width*height<<endl;
cout<<"The surface area is: "<<2*(lengh*width+lengh*height+width*height)<<endl;
}
int main()
{
Bulk b1,b2,b3;
b1.get_value();
cout<<"For bulk1: "<<endl;
b1.display();
b2.get_value();
cout<<"For bulk2: "<<endl;
b2.display();
b3.get_value();
cout<<"For bulk3: "<<endl;
b3.display();
return 0;
}
好好揣摩学习ing~~