gpt4 book ai didi

c++ - 将全局变量更改为引用参数 C++

转载 作者:行者123 更新时间:2023-11-30 01:42:12 25 4
gpt4 key购买 nike

于是,在查了很多网站之后,我终于崩溃了,注册了一个账号。我是新手,也是编程新手,所以请记住这一点 :)

我正在通过制作一个使用欧几里德法求最大公约数的程序来制作递归的经典示例。我还需要跟踪函数调用自身的次数/递归发生的次数。

我的程序运行良好,但我使用全局(非常糟糕!)变量来保存递归计数。我需要用通过我的 gcd 函数传递的引用参数替换全局变量,但我非常不了解它是如何工作的。那是我的问题。有人可以告诉我如何使用引用参数删除全局变量吗?非常感谢!

#include <iostream>
using namespace std;

//Prototype functions
int gcd(int first, int second);

//Global varibles
//Depth will count how many times the recursive function runs.
int depth = 0;

int main ()
{
//variables
int firstNum, secondNum;
do
{
cout << "Welcome to Euclid's method for finding the GCD." << endl << "To quit, enter 0 for either number." << endl;
cout << "Enter the first number:";
cin >> firstNum;
cout << "Enter the second number:";
cin >> secondNum;
//The program quits if the user enters 0. If this happens, the program won't bother with running the recursive function.
if (firstNum != 0 && secondNum != 0)
{
cout << "The GCD of " << firstNum << " and " <<secondNum << " is ";
cout << gcd(firstNum, secondNum) << "." << endl;
cout << "The recursive calculation required a depth of " << depth <<"." << endl;
}
}
while (firstNum != 0 && secondNum != 0); //Program quits on 0 being entered
return (0);
}
//Recursive function. It will call itself until second number is 0.
int gcd(int first, int second)
{
if(second != 0)
{
depth++;
return gcd(second, first % second);
}
else
return first;
}

最佳答案

尝试通过引用传递该参数。

int main ()
{
//variables
int firstNum, secondNum;
int depth = 0;
do
{
cout << "Welcome to Euclid's method for finding the GCD." << endl << "To quit, enter 0 for either number." << endl;
cout << "Enter the first number:";
cin >> firstNum;
cout << "Enter the second number:";
cin >> secondNum;
//The program quits if the user enters 0. If this happens, the program won't bother with running the recursive function.
if (firstNum != 0 && secondNum != 0)
{
cout << "The GCD of " << firstNum << " and " <<secondNum << " is ";
cout << gcd(firstNum, secondNum, depth) << "." << endl;
cout << "The recursive calculation required a depth of " << depth <<"." << endl;
}
}
while (firstNum != 0 && secondNum != 0); //Program quits on 0 being entered
return (0);
}
//Recursive function. It will call itself until second number is 0.
int gcd(int first, int second, int &depth)
{
if(second != 0)
{
depth++;
return gcd(second, first % second, depth);
}
else
return first;
}

关于c++ - 将全局变量更改为引用参数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39982872/

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