任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
我想知道面试官是不是说错了一个问题:不使用循环,计算从1到1000(或从n到m的任意数字)的和。它还教会我们如何分析问题。在C中从1到1000s打印#s总是依赖于在生产程序中可能不会使用的技巧(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;
}
好吧,所以从技术上讲它是一个循环-但它并不比目前为止所有递归的例子更循环;)
我通读了所有这些答案,我的答案与其他答案不同。它是标准C语言,使用整数除法从数组中选择函数指针。此外,它在没有警告的情况下正确编译和执行,甚至在没有警告的情况下传递“夹板”。
当然,我也受到了很多其他答案的启发。即便如此,我的更好。
#include <stdio.h>
#include <stdlib.h>
static int x(/*@unused@*/ const char * format, ...) { exit(0); }
static void p(int v, int e) {
static int (*a[])(const char *, ...) = { printf, x };
(void)a[v/(e+1)]("%d\n", v);
p(v+1, e);
}
int main(void) {
p(1, 1000);
return 0;
}
递归?
#include<stdio.h>
#define MAX 1000
int i = 0;
void foo(void) {
if(i <= 1000) {
printf("%d", i);
i++;
}
}
int main (void) {
foo();
}
你可以非常简单地使用递归和强制错误…
另外,请原谅我的c++代码非常草率。
void print_number(uint number)
{
try
{
print_number(number-1);
}
catch(int e) {}
printf("%d", number+1);
}
void main()
{
print_number(1001);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef void(*word)(int);
word words[1024];
void print(int i) {
printf("%d\n", i);
words[i+1](i+1);
}
void bye(int i) {
exit(0);
}
int main(int argc, char *argv[]) {
words[0] = print;
words[1] = print;
memcpy(&words[2], &words[0], sizeof(word) * 2); // 0-3
memcpy(&words[4], &words[0], sizeof(word) * 4); // 0-7
memcpy(&words[8], &words[0], sizeof(word) * 8); // 0-15
memcpy(&words[16], &words[0], sizeof(word) * 16); // 0-31
memcpy(&words[32], &words[0], sizeof(word) * 32); // 0-63
memcpy(&words[64], &words[0], sizeof(word) * 64); // 0-127
memcpy(&words[128], &words[0], sizeof(word) * 128); // 0-255
memcpy(&words[256], &words[0], sizeof(word) * 256); // 0-511
memcpy(&words[512], &words[0], sizeof(word) * 512); // 0-1023
words[1001] = bye;
words[1](1);
}