任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
适合c++爱好者
int main() {
std::stringstream iss;
iss << std::bitset<32>(0x12345678);
std::copy(std::istream_iterator< std::bitset<4> >(iss),
std::istream_iterator< std::bitset<4> >(),
std::ostream_iterator< std::bitset<4> >(std::cout, "\n"));
}
其他回答
这是我的两个解。第一个是c#,第二个是C语言:
C#:
const int limit = 1000;
Action<int>[] actions = new Action<int>[2];
actions[0] = (n) => { Console.WriteLine(n); };
actions[1] = (n) => { Console.WriteLine(n); actions[Math.Sign(limit - n-1)](n + 1); };
actions[1](0);
C:
#define sign(x) (( x >> 31 ) | ( (unsigned int)( -x ) >> 31 ))
void (*actions[3])(int);
void Action0(int n)
{
printf("%d", n);
}
void Action1(int n)
{
int index;
printf("%d\n", n);
index = sign(998-n)+1;
actions[index](++n);
}
void main()
{
actions[0] = &Action0;
actions[1] = 0; //Not used
actions[2] = &Action1;
actions[2](0);
}
#include <iostream>
using namespace std;
template<int N>
void func()
{
func<N-1>();
cout << N << "\t";
}
template<>
void func<1>()
{
cout << 1 << "\t";
}
int main()
{
func<1000>();
cout << endl;
return 0;
}
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/lambda/lambda.hpp>
#include <iostream>
int main()
{
boost::mpl::for_each<boost::mpl::range_c<unsigned, 1, 1001> >(std::cout << boost::lambda::_1 << '\n');
return(0);
}
显然需要Windows/Visual Studio…但它确实有效。
#include <stdio.h>
#include <Windows.h>
void print(int x)
{
int y;
printf("%d\n", x);
__try
{
y = 1 / (x - 1000);
print(x + 1);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
return;
}
}
void main()
{
print(1);
}
我不打算写代码,只写想法。让一个线程每秒打印一个数字,然后另一个线程在1000秒后杀死第一个线程怎么样?
注:第一个线程通过递归生成数字。