#include <iostream>
// Create count as a static variable and initialize it to 0
static int count = 0;
// Function that increases count by ten
static void IncrementByTen()
{
std::cout<<count<< std::endl;
count+= 10;
}
int main()
{
// As long as count is less or equal to 100
while ( count <= 100 )
{
// Print and increment
IncrementByTen();
}
// Wait for user to hit enter
std::cin.ignore();
return 0;
}
count
现在是一个静态变量,可以从任何函数访问。您也可以自己IncrementByTen()
调用,并在函数本身中添加检查是否超过 100,有点像这样
#include <iostream>
// Function that increases count by ten
static void IncrementByTen()
{
// Create count as a static variable and initialize it to 0 the first time this function is called
static int count = 0;
std::cout<<count<< std::endl;
count+= 10;
if ( count <= 100 )
IncrementByTen();
else
return;
}
int main()
{
// Print and increment
IncrementByTen();
// Wait for user to hit enter
std::cin.ignore();
return 0;
}