gpt4 book ai didi

c++ - 程序不工作,添加它工作的打印语句,为什么?

转载 作者:行者123 更新时间:2023-11-30 02:36:40 24 4
gpt4 key购买 nike

<分区>

我们必须以迭代和递归的方式编写一个 gcd 计算器,我们得到了一个测试脚本,我的程序失败了 2/10 次测试(gcd_iterative(1000, 48) = 1000gcd_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;
}

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com