我编写了一个程序,输出0 3 6 9 12
。现在,我想创建一个叫做reset()
的函数来重置程序,所以它在12之后输出相同的数字。我怎么做呢?
#include <iostream>
using namespace std;
void byThrees();
void reset();
int i = 0;
int main()
{
byThrees();
return 0;
}
void byThrees()
{
while(i<13) {
cout << i << ' ';
i += 3;
}
}
void reset()
{
}
尽量不要使用全局变量!而现在,你可以避免它。
除了byThrees()
,没有人想使用i
。听起来好像您不希望i
的值在byThrees()
的运行中持续存在。所以把它设为函数中的局部变量:
void byThrees()
{
int i = 0;
while(i<13) {
cout << i << ' ';
i += 3;
}
}
现在当你想打印0, 3, 6, 9, ...
系列时,只需调用byThrees()
:
int main() {
byThrees();
std::cout << std::endl; // Add a newline between runs
byThrees();
return 0;
}
另一种方法,如果你想节省内存,只保留一个全局变量(至少我认为这节省内存)是:
#include <iostream>
using namespace std;
int i = 0;
int main()
{
run(); // this function both resets i to 0 and runs byThrees()
return 0;
}
void byThrees()
{
while(i < 13) {
cout << i << ' ';
i += 3;
}
}
void run()
{
i = 0;
byThrees();
}
基本上,无论何时运行函数run()
,您的代码都会将全局变量i重置为0,并将i初始化为0运行byThrees()
。这意味着您可以在代码中重复调用run()
,每次它都会输出0 3 6 9 12
。
如果你的意思是你想要你的代码输出0 3 6 9 12
,然后15 18 21 24 27
在下一次调用(等等),你可以这样做:
#include <iostream>
using namespace std;
int i = 0, nextI = 0; // nextI is a variable that stores the next starting position of i
int main()
{
run(); // will output "0 3 6 9 12"
run(); // will output "15 18 21 24 27"
run(); // will output "30 33 36 39 42"
return 0;
}
void byThrees()
{
while(i < nextI + 13) {
cout << i << ' ';
i += 3;
}
nextI += 15; // increases nextI for the next time "run()" is called
}
void run()
{
i = nextI;
byThrees();
}
这段代码基本上跟踪数字列表的结束位置,并从那里继续。