【问题标题】:I am getting an error in typecasting, please help me out with this我在类型转换中遇到错误,请帮我解决这个问题
【发布时间】:2021-02-21 08:03:50
【问题描述】:

创建一个矩形类。此类具有长度和宽度属性,每个属性默认为 1。它具有计算矩形周长和面积的方法。它具有长度和宽度的设置和获取方法。 set 方法应验证长度和宽度是否为浮点型——点不大于 0.0 且小于 20.0。

#include<iostream>
using namespace std;
class rect
{
    float l;
    float w;
    public:
    void setlw();
    float getl(float len);
    float getw(float width);
    void seta();
    void setp();
};
void rect:: setlw()
{
    cout<<"enter the lenght and width"<<endl;
    cin>>l>>w;
}
float rect:: getl(float len)
{
    if (l>=0.0 && l<=20.0)
    len=l;
    else 
    len=1.0;
    return(len);
}
float rect:: getw(float width)
{
    if(w>=0 && w<=20.0)
    width=w;
    else
    width=1.0;
    return(width);
}
void rect::seta()
{
    float a;
    a=l*w;
    cout<<"the area is"<<a<<endl;
}
void rect:: setp()
{
    float p;
    p=2*(l+w);
    cout<<"the perimeter is"<<p<<endl;
}
int main()
{
    rect r;
    r.setlw();
    cout<<"length is"<<r.getl(float)<<endl;
    cout<<"width is"<<r.getw(float)<<endl;
    r.seta();
    r.setp();
    return (0);
}

【问题讨论】:

  • r.getl(float) 应该做什么?
  • 另外,我是否理解getlgetw 应该返回值 将其保存到传递的参数中?在这种情况下,您需要通过引用传递参数(float getw(float &amp; out)
  • 阅读说明。他们没有说你应该有一个提示用户输入值的函数,他们也没有说任何函数都应该打印任何东西。而且你混淆了“获取”和“设置”。
  • 有人能帮我解决这个问题吗
  • 我是 C++ 初学者

标签: c++ class object


【解决方案1】:

我已更正您的代码。删除了 getl()getw() 的输入参数,因为当您使用 setlw() 进行输入时不需要它。您还没有在函数getlgetw 中声明变量lenwidth

新代码:

#include<iostream>
using namespace std;
class rect
{
    float l;
    float w;
    public:
    void setlw();
    float getl();
    float getw();
    void seta();
    void setp();
};
void rect::setlw()
{
    cout<<"enter the lenght and width"<<endl;
    cin>>l>>w;
}
float rect::getl()
{   float len;
    if (l>=0.0 && l<=20.0)
         len=l;
    else 
         len=1.0;
    return(len);
}
float rect::getw()
{   float width;
    if(w>=0 && w<=20.0)
         width=w;
    else
         width=1.0;
    return(width);
}
void rect::seta()
{
    float a;
    a=l*w;
    cout<<"the area is"<<a<<endl;
}
void rect::setp()
{
    float p;
    p=2*(l+w);
    cout<<"the perimeter is"<<p<<endl;
}
int main()
{
    rect r;
    r.setlw();
    cout<<"length is"<<r.getl()<<endl;
    cout<<"width is"<<r.getw()<<endl;
    r.seta();
    r.setp();
    return (0);
}

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 2014-10-28
    相关资源
    最近更新 更多