首页 > 试题广场 >

请参照以下执行结果实现multiply函数。

[问答题]
请参照以下执行结果实现multiply函数。
multiply(2,5)//returns
10
multiply(2)(5)//returns
10
推荐

int  multiply( int  a,  int  b) {

     return  a * b;

}

function < int  ( int )> multiply( int  a) {

     return  [=]( int  b) {

         return  a * b;

    };

}

int  main() {

     cout  <<  multiply ( 2 5 ) <<  endl ;

     cout  <<  multiply ( 2 )( 5 ) <<  endl ;

     return   0 ;

}

编辑于 2017-05-23 17:18:06 回复(0)

考察闭包

def multiply(a, b=False):
    def multy(b):
        return a*b
    if isinstance(b,int) and isinstance(b,bool):
        '''
        如果b=FALSE,那么返回multy这个函数:
        用两个isinstance是为了判断b=0还是b=False
        isinstance(0,bool)=False,isinstance(False,bool)=true
        multiply(2)(5) -> (a=5,b=False) ->multy(5)-> 10
        '''
        return multy
    else:
        return a*b
编辑于 2017-06-23 16:43:05 回复(2)