不使用循环或条件语句输出1到1000
Page 1 of 1
不使用循环或条件语句输出1到1000
"不使用循环或条件语句输出1到1000"不使用loop语句输出1到1000"是在网络上常常有人讨论的热门题目
这里整理了几个看起来不错的方法
这个使用了递归的方法,但却使用了条件语句
使用构造函数的方法
使用template
还有一种简短的方法,但C++不适用,C适用
这里整理了几个看起来不错的方法
这个使用了递归的方法,但却使用了条件语句
- Code:
#include <iostream>
using namespace std;
void f(int n)
{
cout<<n<<endl;
(1000-n) ? f(n+1) : exit(0) ; //当n 为 1000 时,1000-1000 的结果就会是0(也就是false),这时 exit(0)就会被调用
}
int main()
{
f(1);
return 0;
}
使用构造函数的方法
- Code:
#include <iostream>
using namespace std;
class A
{
public:
static int count;
A()
{
cout << count++ <<endl;
}
};
int A::count = 1; //静态变量
int main()
{
A obj[1000]; //调用1000次构造函数
return 0;
}
使用template
- Code:
#include <iostream>
using namespace std;
template<int N>
struct NumberGeneration
{
static void out(ostream& os)
{
NumberGeneration<N-1>::out(os);
os << N << endl;
}
};
template<>
struct NumberGeneration<1>
{
static void out(ostream& os)
{
os << 1 << endl;
}
};
int main()
{
NumberGeneration<1000>::out(cout);
return 0;
}
还有一种简短的方法,但C++不适用,C适用
- Code:
void main(int j)
printf("%d\n", j);
(main + (exit - main)*(j/1000))(j+1);
}
too wei- Sponsor
- Posts : 31
Points : 66331
Reputation : 0
Join date : 2015-04-21
Age : 25
Location : Johor
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|