了解在不使用乘法运算符的情况下实现 square() 的解决方案



我目前正在研究Bjarne Stroustrup的编程原理和实践使用C++。"试试这个"练习之一是在不使用乘法运算符的情况下实现平方函数。我找到的解决方案是:

int archaic_square(int v) {
int total = 0;
for (int i = 0; i < v; ++i) {
total += v;
}
return total;
}
int main() {
for (int i = 0; i < 100; ++i) {
cout << i << 't' << archaic_square(i) << 'n';
}
}

我知道这有效并输出从 0 到 99 的整数平方,但我不明白它是如何工作的。有人可以解释一下函数输出的确切内容以及变量total作为v增量是什么吗?

我试着在纸上做,然后解决。假设v递增 1,函数中输入v = 2如何返回 4?每当我手工解决时,我似乎都会得到 3

。我确信这是一个非常简单的问题,我刚刚开始并试图理解这种语言。

当你有疑问时,我建议你打印出函数内每次迭代的值,

int archaic_square(int v) {
int total = 0;
for (int i = 0; i < v; ++i) {
total += v;
std::cout << "total= " << total << " where i= " << i << " n"; // --- HERE ----
}
return total;

}

您应该看到输出为

2  where i= 0
4  where i= 1

(当 v 作为 2 传入时)

在函数archaic_square中,我从 0 开始,这个 for 循环重复v次,每次总数都变成totalv,就像v * v

int archaic_square(int v) {
int total = 0;

for (int i = 0; i < v; i++) {
total += v;
}

return total;
}

这很简单,你可以把乘法想象成: 例如,我说3 * 5它等同于我说5 + 5 + 53 + 3 + 3 + 3 +3.

与此函数N数字求和N次的方式相同。例如,假设我通过v=5. 它将像这样工作:total= 5 + 5 + 5 + 5 + 5 = 25.

数字的平方与将该数字相加与该数字相同的次数相同。这就是archaic_square(int v)total的目的,嗯,是为自己增加vv次的总和。v在此函数中不会递增 1,i是。

main调用此函数时,i从 0 开始,每个循环向自身添加 1,并在i小于 100 时继续。当它是 100 时,它不小于 100,因此它停止在 99。

重要的是要注意,archaic_square中的i与 main 中的i不同 - 这是变量的范围。他们彼此不认识。重要的是要注意,这是int i重要的地方。如果您只使用i那么它将期望在该范围之外的其他地方定义一个i- 如果您在此处执行此操作,如果您这样做然后全局定义i,它们会相互干扰,整个事情会中断。

i通常用作循环变量名(iteration)。 所以你会经常看到这一点。

因此:控制台上打印从 0 到 99 的正方形。

作为一个初学者,这是我在经历了很多挠头之后对这个解决方案的理解,我觉得我在这个函数代码中的评论对于初学者来说是一个很好的解释!

int archaic_square(int v) 
{
int total =0;
for (int i = 0; i < v; ++i) //this loop will repeat v times (until i is less than v; keep increasing i)
{
total += v; 
/*Let us take the example of v = 5. So variable 'i' (which is in the for loop) will keep incrementing by 1 if value is less than 5.
So loop will repeat 5 times. So each time loop repeats the new value of total will become  
total = (total +5). This process will repeat 5 times. As value of the variable total is zero, the final value of total will be: 
(total + 5) + (total + 5) + (total + 5) + (total + 5) + (total + 5).
[Since total value is 0, 5 is getting added 5 times, which is 25 which is 5 times 5] 
Hence, this loop is doing multiplication.*/
}
return total;
}

祝您编码愉快!

相关内容

最新更新