C ++ - 递归计数器

时间:2017-12-06 22:50:10

标签: c++ recursion

我正在尝试创建一个计数器。它计算每个操作,如乘法,加法,减法,除法。每次我尝试小计时,它都会保持为零。

任何人都可以了解我做错了什么吗?

我的大部分代码都丢失了,所以我可以保护它免受其他同学的影响,但是我已经列出了代码所在部分的操作数量。

long karatsuba(int num1, int num2, int &counter)
{
 if (num1 < 10 || num2 < 10)
 {
    counter++ // 1 operation
    return num1 * num2;
 }
 /* calculates the size of the number */
 ... 4 operations

 /* split the digit sequences about the middle */
 ... 4 operations

 /* 3 calls made to numbers approximately half the size */
 int z0 = karatsuba(..., ..., counter);
 int z1 = karatsuba(..., ..., counter);
 int z2 = karatsuba(..., ..., counter);


 return ... // 9 operations
}
-------------------------------------------------------------
int main()
{
 int counter = 0;
 cout << karatsuba(123, 456, counter) << " " << counter << endl;

 cout << endl;
 system("Pause");
 return 0;
}

1 个答案:

答案 0 :(得分:2)

问题在于这一行:

cout << karatsuba(123, 456, counter) << " " << counter << endl;

尝试改为 cout << karatsuba(123, 456, counter); cout << " " << counter << endl;

问题是cout,打印时count仍为0。