在C ++中制作不带x * x的square()函数 [英] Making a square() function without x*x in C++
问题描述
我正在自学C ++和Bjarne Stroustrup撰写的《使用C ++的编程原理和实践》一书。 尝试使用此方法之一问:
I am self-studying C++ and the book "Programming-Principles and Practices Using C++" by Bjarne Stroustrup. One of the "Try This" asks this:
不使用乘法运算符而实现square();也就是说,通过重复加法来执行x * x(将
变量结果从0开始,然后将x加x倍)。然后使用该square()运行某个版本的第一个程序。
Implement square() without using the multiplication operator; that is, do the x*x by repeated addition (start a variable result at 0 and add x to it x times). Then run some version of "the first program" using that square().
基本上,我需要制作一个square(int x)函数,该函数将返回它不使用乘法运算符。我到目前为止有这个:
Basically, I need to make a square(int x) function that will return the square of it without using the multiplication operator. I so far have this:
int square(int x)
{
int i = 0;
for(int counter = 0; counter < x; ++counter)
{
i = i + x;
}
return i;
}
但是我想知道是否有更好的方法可以做到这一点。上面的函数有效,但是我坚信这不是最好的方法。有帮助吗?
But I was wondering if there was a better way to do this. The above function works, but I am highly sure it is not the best way to do it. Any help?
推荐答案
彼得森(Petersson)甚至在我想到之前就把这个想法从我脑海中偷走了。
Mats Petersson stole the idea out of my head even before I thought to think it.
#include <iostream>
template <typename T>
T square(T x) {
if(x < 0) x = T(0)-x;
T sum{0}, s{x};
while(s) {
if(s & 1) sum += x;
x <<= 1;
s >>= 1;
}
return sum;
}
int main() {
auto sq = square(80);
std::cout << sq << "\n";
}
这篇关于在C ++中制作不带x * x的square()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!