Making a square() function without x*x in C++

后端 未结 7 2132
攒了一身酷
攒了一身酷 2020-12-31 14:44

I am self-studying C++ and the book \"Programming-Principles and Practices Using C++\" by Bjarne Stroustrup. One of the \"Try This\" asks this:

Implement square() wi

7条回答
  •  梦谈多话
    2020-12-31 15:27

      //Josef.L
      //Without using multiplication operators.
    
    int square (int a){
         int b = 0; int c =0;
        //I don't need to input value for a, because as a function it already did it for me.
        /*while(b != a){
                b ++;
            c = c + a;}*/
        for(int b = 0; b != a; b++){  //reduce the workload.
            c = c +a;
            //Interesting, for every time b is not equal to a, it will add one to its value:
            //In the same time, when it add one new c = old c + input value will repeat again.
            //Hence when be is equal to a, c which intially is 0 already add to a for a time.
            //Therefore, it is same thing as saying a * a.
        }
        return c;
    }
    
    int main(void){
        int a;
        cin >>a;
        cout <<"Square of: "<

提交回复
热议问题