任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
更多的预处理程序滥用:
#include <stdio.h>
#define A1(x,y) #x #y "0\n" #x #y "1\n" #x #y "2\n" #x #y "3\n" #x #y "4\n" #x #y "5\n" #x #y "6\n" #x #y "7\n" #x #y "8\n" #x #y "9\n"
#define A2(x) A1(x,1) A1(x,2) A1(x,3) A1(x,4) A1(x,5) A1(x,6) A1(x,7) A1(x,8) A1(x,9)
#define A3(x) A1(x,0) A2(x)
#define A4 A3(1) A3(2) A3(3) A3(4) A3(5) A3(6) A3(7) A3(8) A3(9)
#define A5 "1\n2\n3\n4\n5\n6\n7\n8\n9\n" A2() A4 "1000\n"
int main(int argc, char *argv[]) {
printf(A5);
return 0;
}
我觉得好脏;我想我现在要去洗澡了。
其他回答
您可以使用System()打印1到1000(通过使用DOS命令)
include <process.h>
void main()
{
system("cmd.exe /c for /l %x in (1, 1, 1000) do echo %x" );
}
运行程序的.exe(可执行)文件,显示1到1000
注意:在WINDOWS中测试
#include <iostream>
#include <vector>
using namespace std;
#define N 10 //10 or 1000, doesn't matter
class A{
public:
A(){
//cout << "A(): " << m_ << endl; //uncomment to show the difference between gcc and Microsoft C++ compiler
}
A(const A&){
++m_;
cout << m_ << endl;
}
private:
static int m_; //global counter
};
int A::m_(0); //initialization
int main(int argc, char* argv[])
{
//Creates a vector with N elements. Printing is from the copy constructor,
//which is called exactly N times.
vector<A> v(N);
return 0;
}
实现注意: 使用gcc:默认构造函数创建一个“master”元素。 然后元素被复制构造函数复制N次。 在微软c++编译器中:所有元素都是由默认构造函数创建的 然后被复制构造函数复制。
我认为这些代码工作完全正确,很容易理解,你可以打印任何像1到100或1到最终范围。把它放在I中,然后转移到call function中。
int main()
{
int i=1;
call(i,i);
}
void call(int i,int j)
{
printf("%d",i);
sleep(1); // to see the numbers for delay
j /= (j-1000);
j = ++i;
call(i,j);
}
所以当j等于1000时,它会被除零,然后直接退出程序这就是我打印数字的想法
或者更简单的代码..
int main()
{
static int i = 1;
static int j = 1;
printf("%d", i);
sleep(1);
j = ++i;
j /= (j-1000);
main();
}
我假设,由于这个问题的性质,扩展是不排除的?
而且,我很惊讶,到目前为止还没有人去。
int main () {
int i = 0;
void * addr[1001] = { [0 ... 999] = &&again};
addr[1000] = &&end;
again:
printf("%d\n", i + 1);
goto *addr[++i];
end:
return 0;
}
好吧,所以从技术上讲它是一个循环-但它并不比目前为止所有递归的例子更循环;)
Manglesky的解决方案很棒,但还不够模糊。: -):
#include <stdio.h>
#define TEN(S) S S S S S S S S S S
int main() { int i = 1; TEN(TEN(TEN(printf("%d\n", i++);))) return 0; }