我是c++的新手,我试图在另一个类中调用一个类的函数,但输出就是不正确。我试着根据不同的区域反复计算总成本,但输出总是乱码。我想我已经声明过了?这是我的代码:
#include<iostream>
#include<math.h>
#include<stdlib.h>
#include<iomanip>
#include<numeric>
#include<conio.h>
using namespace std;
class RoomDimension
{
public:
double width;
double length;
double area;
double getarea(void);
void room(int,int);
};
double RoomDimension::getarea()
{
return area;
}
class RoomCarpet: public RoomDimension
{
public:
double costpermeter;
double totalcost=0;
double gettotalcost(void);
void calculation();
};
double RoomCarpet ::gettotalcost()
{
return totalcost;
}
void RoomDimension::room(int n, int m)
{
RoomCarpet rc;
cout<<"Number of rooms= ";
cin>>m;
if(m<1)
{
cout<<"Invalid input."<<endl;
}
for (n = 0;n < m;++n)
{
cout<<"Length of the room= ";
cin>>length;
if(length==0)
{
cout<<"Invalid input.";
return;
}
cout<<"Width of the room= ";
cin>>width;
if(width==0)
{
cout<<"Invalid input.";
return;
}
area=width*length;
cout<<"Area of the room= "<<area<<endl;
rc.calculation();
}
return;
}
void RoomCarpet::calculation()
{
RoomDimension rd;
totalcost=0;
cout<<"Price per square meter= ";
cin>>costpermeter;
if(costpermeter==0)
{
cout<<"Invalid input."<<endl;
return;
}
double totalcost=costpermeter*rd.area;
cout<<"Total price= RM"<<totalcost<<endl;
return;
}
int main()
{
RoomDimension rd;
rd.room(0,0);
return 0;
}输出结果如下所示
Number of rooms= 2
Length of the room= 5
Width of the room= 4
Area of the room= 20
Price per square meter= 5
Total price= RM5.03097e-317
Length of the room= 3
Width of the room= 7
Area of the room= 21
Price per square meter= 7
Total price= RM7.04336e-317我该怎么做才能解决这个问题呢?
发布于 2020-10-29 15:46:33
当我使用MSVC编译你的代码时,我得到两个警告和一个错误:
特别是最后一个是个问题
在函数RoomCarpet::calculation中,您(至少)犯了两个错误:
声明并使用隐藏类成员Roomcarpet::totalcost.的局部变量totalcost时,您可以声明一个从不是initialized.
rd但是在RoomDimension::room中也会出现这个问题,您可以从声明局部变量rc开始,但是从来没有给它赋值。然后,当您调用rc.calculation();时,您将对无符号变量进行计算。
你应该重新考虑你的设计。为什么RoomCarpet是RoomDimension的派生
https://stackoverflow.com/questions/64585256
复制相似问题