用++操作符完成其它操作符的轉換,操作符完成轉換

來源:互聯網
上載者:User

用++操作符完成其它操作符的轉換,操作符完成轉換

在只容許使用++操作符的情況下,請完成下面代碼,實現減法、乘法和除法。注意:假設運算元全為正整數,並且可以不考慮效能,不能使用–,*,/等操作符。
a). 乘法: int multi(int opl,int op2){//op1*op2}
b). 減法: intsub(int op1,int op2){//op1-op2}
c). 除法: int div(int op1,int op2){//op1/op2}

中心思想:利用for迴圈來實現不能用其它操作符的短板 int multi(int opl,int op2)//op1*op2 {      int mu = op1 ;      for ( int i = 1 ; i < op2 ; i ++)//控制外層迴圈個數,也可以和op1交換位置,但是如果換了就要把mu賦值也換了,它小於op2而不是等於是因為前面mu已經被賦值一次          for ( int j = 1 ; j <= op1 ; j ++)             mu ++;      return mu ; }int sub(int op1,int op2)//op1-op2intsub(in top1,int op2) {    int n=0;    for( int i=op2;i<op1;++i )  {       n++;    }    return n;}int div(int op1,int op2)//op1/op2 {     int di = 1;    int temp = op2 ;      while ( op1  >= op2 )//這裡如果假設op2是小一點的數會更好的理解。      {          for ( int i = 0 ; i < temp ; i ++)        op2 ++;//利用自身迴圈和加一的特點,如果自己轉完加到了temp一次,就表明滿足一次,di就++一次,每次加一,然後判斷op1是否等於op2,如果不等於,繼續迴圈,如果等於,退出返回di。        di ++;      }      return  di ; } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.