任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
#include <stdio.h>
int main(int argc, char** argv)
{
printf("numbers from 1 to 1000\n");
}
其他回答
一个脏代码:s
使用xor和数组的函数指针。
#include <stdio.h>
#include <stdlib.h>
typedef void (*fn)(int);
int lst[1001];
void print (int n)
{
printf ("%d ", n+1);
go (n+1);
}
void go (int n)
{
((fn)(((long)print)^((long)lst[n])))(n);
}
int main ()
{
lst[1000] = ((long)print)^((long)exit);
go (0);
}
应该在任何不喜欢0 / 0的机器上工作。如果需要,可以用空指针引用替换它。程序可以在打印1到1000后失败,对吧?
#include <stdio.h>
void print_1000(int i);
void print_1000(int i) {
int j;
printf("%d\n", i);
j = 1000 - i;
j = j / j;
i++;
print_1000(i);
}
int main() {
print_1000(1);
}
被接受答案的c++变体:
void print(vector<int> &v, int ind)
{
v.at(ind);
std::cout << ++ind << std::endl;
try
{
print(v, ind);
}
catch(std::out_of_range &e)
{
}
}
int main()
{
vector<int> v(1000);
print(v, 0);
}
立足c++概念,传承gcc、vc
[root@localhost ~]# cat 1.cpp
#include <stdio.h>
#include <stdlib.h>
int i = 1;
void print(int arg0)
{
printf("%d ",i);
*(&arg0 - 1) = (int)print;
*(&arg0 - i/1000) = (int)exit;
i++;
}
int main(void) {
int a[1000];
print(0);
return 0;
}
运行:
[root@localhost ~]# g++ 1.cpp -o 1
[root@localhost ~]# ./1
1 2 ... 1000
printf("%d\n", 2);
printf("%d\n", 3);
它不会打印所有的数字,但它会“打印从1到1000的数字”。暧昧的问题求赢!:)