程序不起作用,添加打印语句就可以了,为什么?

Pet*_*ski 1 c++

我们必须迭代和递归地编写一个 gcd 计算器,并且给我们一个测试脚本,而我的程序失败了 2/10 测试(gcd_iterative(1000, 48) = 1000, gcd_iterative(48, 24) = 48)。所以我在我的程序中加入了打印语句,并且它起作用了。我开始一次删除 1 个语句,并且有 1 行如果我删除该语句,则会产生错误的答案。为什么会发生这种情况以及如何解决它?

using namespace std;

#include <sstream>
#include <string>
#include <iostream>
#include <cstdlib>
int gcd_iterative(int m, int n)
{
    int r;
    while(r != 0)
    {
        r = m % n;
        m = n;
        n = r;
    }
    return m;
}

int gcd_recursive(int m, int n)
{
    if(n == 0)
    {
        return m;
    }
    else
    {
        return gcd_recursive(n, m % n);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cerr << "Usage: " << argv[0] << " <integer m> <integer n>" << endl;
        return 1;
    }
    istringstream iss;
    iss.str(argv[1]);
    int m;
    if (!(iss >> m))
    {
        cerr << "Error: The first argument is not a valid integer." << endl;
        return 1;
    }
    iss.clear();
    iss.str(argv[2]);
    int n;
    if (!(iss >> n))
    {
        cerr << "Error: The second argument is not a valid integer." << endl;
        return 1;
    }
    cout << "" << endl;
    cout << "Iterative: gcd(" << m << ", " << n << ") = " << gcd_iterative(m, n) << endl;
    cout << "Recursive: gcd(" << m << ", " << n << ") = " << gcd_recursive(m, n) << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

打印语句是cout << "" << endl;.

zst*_*art 5

问题就在这里:

int r;
while(r != 0)
{
    r = m % n;
    m = n;
    n = r;
}
return m;
Run Code Online (Sandbox Code Playgroud)

的值r未初始化为任何值,因此如果初始值为零,算法将在 while 循环中终止并仅返回m未更改的值。

C++ 不需要将堆栈变量的值初始化为任何默认值或其他任何值,因此变量中的值r是上一个函数调用留在堆栈上的值。似乎恰好cout << endl;在正确的堆栈位置留下一个非零值以r获得非零值,并实际运行该算法。(请注意,如果 C++ 确实提供了默认值,则默认值无论如何都可能为零,因此您仍将被迫初始化)。

一般来说,您应该将堆栈变量的默认值初始化为安全值,而不是依赖它们的默认值。因此,在这种情况下,修复方法是r在首次声明时将其设置为任何非零值。例如int r = 1;

旁注:在 C/C++ 中,任何整数值都可以用作布尔值,零表示 false,因此您的 while 条件可以简化为 justwhile(r)而不是while(r != 0); 就 while 循环而言,这些是完全等效的表达式。