我想使用以下代码计算矩形的面积和周长:
rect a;
a = ( -----
! !
-----a );
std::cout << a.area() << std::endl;
std::cout << a.perimeter() << std::endl;
为此,我制作了以下类(class):
class rect
{
public:
rect():w(0), h(2) {}
rect& operator - () { w += 0.5f; return *this; }
rect& operator - (rect&) { w += 0.5f; return *this; }
rect& operator -- (int a) { w += a; return *this; }
rect& operator -- () { w += 1; return *this; }
rect& operator ! () { h += 0.5f; return *this; }
void clear() { w = 0; h = 2; }
int area() { return w * h; }
int perimeter() { return 2 * w + 2 * h; }
int width() { return w; }
int height() { return h; }
private:
float w;
float h;
};
以下是一些用法示例:
#include <iostream>
int main()
{
rect a;
a = ( -----
! !
-----a );
std::cout << a.area() << std::endl;
std::cout << a.perimeter() << std::endl;
std::cout << a.width() << std::endl;
std::cout << a.height() << std::endl;
std::cout << std::endl;
a.clear();
a = ( ----------
! !
! !
! !
! !
---------a );
std::cout << a.area() << std::endl;
std::cout << a.perimeter() << std::endl;
std::cout << a.width() << std::endl;
std::cout << a.height() << std::endl;
return 0;
}
这是我的问题:
- 可以不涉及任何浮点运算吗? (确实是整数网格)
能否在 3D 案例上进行概括?即:
cuboid b; b = ( --------- / /! ! -------! ! ! ! ! ! ! ! ! !/ ---------b ); std::cout << b.volume() << std::endl;
最佳答案
我不得不将“/”运算符更改为“+”,因为没有前缀“/”运算符。 + 虽然效果很好。哦,它使用整数。我只用您提供的案例对其进行了一次测试,但据我所知它应该可以工作。
class cuboid
{
int w,h,l;
public:
cuboid () : w(2), h(3), l(6) {}
cuboid& operator - () { w += 1; return *this; }
cuboid& operator - (cuboid&) { w += 1; return *this; }
cuboid& operator -- (int) { w += 2; return *this; }
cuboid& operator -- () { w += 2; return *this; }
cuboid& operator ! () { h += 1; return *this; }
cuboid& operator + () { l += 1; return *this; }
cuboid& operator + (cuboid&) { l += 1; return *this; }
cuboid& operator ++ () { l += 2; return *this; }
cuboid& operator ++ (int) { l += 2; return *this; }
void clear () { w = 2; h = 3; l = 6; }
int width () const { return w / 3; }
int height () const { return h / 3; }
int length () const { return l / 3; }
int volume () const { return width() * height () * length (); }
int surface_area() const { return width() * height () * 2 +
width() * length () * 2 +
length() * height () * 2; }
};
查看它的实际应用。 http://ideone.com/vDqEm
编辑:您不需要++ 运算符,因为不应该有两个 + 彼此相邻。哎呀。
关于c++ - C/C++ : Perimeter and area of rects. 长方体的体积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11615606/