2021-05-26 14:16

# 求c++代码大佬来看看

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 4条回答默认 最新

• qfl_sdu 2021-05-26 14:35
已采纳

代码如下，如有帮助，请采纳一下，谢谢。

``````#include <stdio.h>

class Rectangle
{
private:
int width,height;
public:
Rectangle(){width = 1; height = 1;}
Rectangle(int width,int height):width(width),height(height){}
int getWidth(){return width;}
int getHeight(){return height;}
void setWidth(int newWidth){width = newWidth;}
void setHeight(int newHeight){height = newHeight;}
int getArea(){return width * height;}
int getPerimeter(){return 2*(width + height);}

friend void print_Rectangle(Rectangle* p);

};

void print_Rectangle(Rectangle* p)
{
printf("width=%d;height=%d\n",p->width,p->height);
}

int main()
{
Rectangle r1(4,40);
Rectangle r2(3.5,35.9);
printf("r1的宽=%d;高=%d;面积=%d;周长=%d\n",r1.getWidth(),r1.getHeight(),r1.getArea(),r1.getPerimeter());
printf("r2的宽=%d;高=%d;面积=%d;周长=%d\n",r2.getWidth(),r2.getHeight(),r2.getArea(),r2.getPerimeter());
//
printf("友元函数测试：\n");
Rectangle r3(4,5);
print_Rectangle(&r3);
//getchar();
//getchar();
return 0;
}``````
点赞 评论
``````class Rectangle
{
private:
float width;
float height;
public:
Rectangle() { width = height = 1; }
Rectangle(float w, float h) { width = w; height = h; }
float getWidth() { return width; }
float getHeight() { return height; }
void setWidth(float w) { width = w; }
void setHeight(float h) { height = h; }
float getArea() { return width*height; }
float getPerimeter() { return 2 * (width + height); }
friend  void print_Rectangle(Rectangle &r) { printf("width=%g,height=%g\n", r.width, r.height); }
};

int main()
{
Rectangle r1(4, 40);
Rectangle r2(3.5, 35.9);
printf("矩形r1长=%g，宽=%g，面积=%g,周长=%g\n", r1.getWidth(), r1.getHeight(), r1.getArea(), r1.getPerimeter());
printf("矩形r2长=%g，宽=%g，面积=%g,周长=%g\n", r2.getWidth(), r2.getHeight(), r2.getArea(), r2.getPerimeter());
Rectangle r3(10, 30.2);
print_Rectangle(r3);

return 0;
}``````
点赞 评论

题主，你确定采纳的代码能用吗？长和宽都是小数，用%d输出你能用啊？

点赞 评论
• 有问必答小助手 2021-05-26 16:53

您好，我是有问必答小助手，您的问题已经有小伙伴解答了，您看下是否解决，可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案，可以点击【采纳】按钮，给回答的小伙伴一些鼓励哦～～