gpt4 book ai didi

c++ - 表面积/体积

转载 作者:行者123 更新时间:2023-11-28 00:19:18 28 4
gpt4 key购买 nike

我正在尝试让这段代码计算盒子的表面积和体积。它编译但不输出正确的数据。我认为问题可能出在 void Box::零件内,但碰壁了。或者它可能是 Height = Height 但我无法以任何其他方式让它运行而不会出错。

代码如下:

#include <iostream>
#include "Box.hpp"

using namespace std;


int main()
{
Box box;
double boxHeight, boxWidth, boxLength;

cout << "This program will tell you the surface area and volume of a box" << endl;
cout << "Please enter the height " << endl;
cin >> boxHeight;
cout << "Please enter the width " << endl;
cin >> boxWidth;
cout << "Please enter the length" << endl;
cin >> boxLength;

box.setHeight();

cout << "The surface area is " << box.getSurfaceArea() << endl;
cout << "The volume is " << box.getVolume() << endl;


return 0;
}

void Box::setHeight(){
if(Height< 0)
cout << "Error. Must enter a positive number " << endl;
else
Height = Height;
}


void Box::setLength(){
if(Length< 0)
cout << "Error. Must enter a positive number " << endl;
else
Length = Length;
}


void Box::setWidth(){
if(Width< 0)
cout << "Error. Must enter a positive number " << endl;
else
Width = Width;
}


double Box::getSurfaceArea(){

return 2*(Length*Width) + 2*(Length*Height) + 2*(Width + Height);
}



double Box::getVolume(){

return Length*Width*Height;
}

hpp 文件是这样的:

#ifndef BOX_HPP_INCLUDED
#define BOX_HPP_INCLUDED

class Box
{
public:
void setHeight();
void setWidth();
void setLength();
double getVolume();
double getSurfaceArea();

private:
double Length;
double Width;
double Height;
};


#endif

最佳答案

首先,您需要在您的 setter 中传递您想要设置的值:

void setHeight(double height);
void setWidth(double width);
void setLength(double length);

void Box::setHeight(double height)
{
if(height < 0)
cout << "Error. Must enter a positive number " << endl;
else
Height = height;
}

void Box::setWidth(double width)
{
if(width < 0)
cout << "Error. Must enter a positive number " << endl;
else
Width = width;
}

void Box::setLength(double length)
{
if(length < 0)
cout << "Error. Must enter a positive number " << endl;
else
Length = length;
}

此外,您不仅需要设置框的高度,还需要设置框的宽度和长度:

box.setHeight(boxHeight);
box.setWidth(boxWidth);
box.setLength(boxLength);

这应该可以解决问题。

关于c++ - 表面积/体积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28390860/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com