怎样用5毫升的量杯和3毫升的量杯量出4毫升的水用c语言写出来
怎样用5毫升的杯子和3毫升的杯子量出4毫升的水用c语言写出来,水是无限制的,但是工具只有这两个量杯。
办法想到了一个,中文是这样的,
a、先将5毫升的水倒入3毫升的水杯,再把3毫升的水杯里的水倒掉,那么五毫升的水杯里只有2毫升的水了
b、把5毫升里2毫升的水倒入3毫升的水杯,那么3毫升的水杯里就只有2毫升的水
c、再把5毫升的水杯装满,这样把5毫升的水倒入已经装有有2毫升水的3毫升量杯直到3毫升的量杯装满,
那么5毫升的量杯中就有4毫升的水了
[解决办法]
纠正:
此时:5升杯中就是我们需要的4升水
[解决办法]
修正版:
#include "stdio.h"#define min( x, y ) ((( x ) < ( y )) ? ( x ) : ( y ))class CGlass{public: CGlass( int nSize, int nWater = 0 ) : m_nSize( nSize ), m_nWater( nWater ){} ~CGlass(){} void Eject( int nWater = 0 ) { if( nWater == 0 ) m_nWater = 0; else { m_nWater -= nWater; if( m_nWater < 0 ) m_nWater = 0; } } void Inject( int nWater = 0 ) { if( nWater == 0 ) m_nWater = m_nSize; else { m_nWater += nWater; if( m_nWater > m_nSize ) m_nWater = m_nSize; } } int GetSize() const { return m_nSize; } int GetWater() const { return m_nWater; } int operator>>( CGlass& other ) { int w = min( m_nWater, ( other.GetSize() - other.GetWater())); Eject( w ); other.Inject( w ); return m_nWater; } int operator<<( CGlass& other ) { int w = min( m_nSize - m_nWater, other.GetWater()); Inject( w ); other.Eject( w ); return m_nWater; }protected: int m_nSize; int m_nWater;};int _tmain(int argc, _TCHAR* argv[]){ CGlass g5( 5, 5 ); CGlass g3( 3 ); g5 >> g3; g3.Eject(); g5 >> g3; g5.Inject(); g5 >> g3; printf( "G5 left water is : %d", g5.GetWater()); getchar(); return 0;}