任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
c++利用RAII
#include <iostream>
using namespace std;
static int i = 1;
struct a
{
a(){cout<<i++<<endl;}
~a(){cout<<i++<<endl;}
}obj[500];
int main(){return 0;}
C语言开发宏
#include <stdio.h>
#define c1000(x) c5(c5(c5(c4(c2(x)))))
#define c5(x) c4(x) c1(x) //or x x x x x
#define c4(x) c2(c2(x)) //or x x x x
#define c2(x) c1(x) c1(x) //or x x
#define c1(x) x
int main(int i){c1000(printf("%d\n",i++);)return 0;}
编辑:还有一个,这个很简单
#include <stdio.h>
#define p10(x) x x x x x x x x x x
int main(int i){p10(p10(p10(printf("%d\n",i++);)))return 0;}
解析:选C
编辑:此c代码包含<=和?:操作符
#include <stdio.h>
int main(int i){return (i<=1000)?main(printf("%d\n",i++)*0 + i):0;}
其他回答
我认为这些代码工作完全正确,很容易理解,你可以打印任何像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();
}
这只使用O(log N)堆栈,并使用麦卡锡评估http://en.wikipedia.org/wiki/Short-circuit_evaluation作为其递归条件。
#include <stdio.h>
int printN(int n) {
printf("%d\n", n);
return 1;
}
int print_range(int low, int high) {
return ((low+1==high) && (printN(low)) ||
(print_range(low,(low+high)/2) && print_range((low+high)/2, high)));
}
int main() {
print_range(1,1001);
}
未经测试,但应该是香草标准C:
void yesprint(int i);
void noprint(int i);
typedef void(*fnPtr)(int);
fnPtr dispatch[] = { noprint, yesprint };
void yesprint(int i) {
printf("%d\n", i);
dispatch[i < 1000](i + 1);
}
void noprint(int i) { /* do nothing. */ }
int main() {
yesprint(1);
}
这个实际上编译为没有任何条件的程序集:
#include <stdio.h>
#include <stdlib.h>
void main(int j) {
printf("%d\n", j);
(&main + (&exit - &main)*(j/1000))(j+1);
}
编辑:添加了'&',因此它将考虑地址,从而避免指针错误。
上面的这个版本在标准C中,因为它不依赖于函数指针的算术:
#include <stdio.h>
#include <stdlib.h>
void f(int j)
{
static void (*const ft[2])(int) = { f, exit };
printf("%d\n", j);
ft[j/1000](j + 1);
}
int main(int argc, char *argv[])
{
f(1);
}
如果POSIX解决方案被接受:
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>
static void die(int sig) {
exit(0);
}
static void wakeup(int sig) {
static int counter = 1;
struct itimerval timer;
float i = 1000 / (1000 - counter);
printf("%d\n", counter++);
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 0;
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = i; /* Avoid code elimination */
setitimer(ITIMER_REAL, &timer, 0);
}
int main() {
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
signal(SIGFPE, die);
signal(SIGALRM, wakeup);
wakeup(0);
pthread_mutex_lock(&mutex);
pthread_mutex_lock(&mutex); /* Deadlock, YAY! */
return 0;
}