任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
易如反掌!: P
#include <iostream>
static int current = 1;
struct print
{
print() { std::cout << current++ << std::endl; }
};
int main()
{
print numbers [1000];
}
其他回答
递归?
#include<stdio.h>
#define MAX 1000
int i = 0;
void foo(void) {
if(i <= 1000) {
printf("%d", i);
i++;
}
}
int main (void) {
foo();
}
#include "stdafx.h"
static n=1;
class number {
public:
number () {
std::cout << n++ << std::endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
number X[1000];
return 0;
}
这只使用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);
}
我不打算写代码,只写想法。让一个线程每秒打印一个数字,然后另一个线程在1000秒后杀死第一个线程怎么样?
注:第一个线程通过递归生成数字。
尽管在这里看到了所有出色的代码,但我认为唯一真正的答案是它不能实现。
为什么?简单。事实上,每一个答案都是循环的。隐藏为递归的循环仍然是循环。看一下汇编代码就会发现这一事实。即使读取和打印带有数字的文本文件也涉及循环。再看一下机器代码。输入1000个printf语句也意味着循环,因为printf本身也有循环。
不可能做到。