任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
template <int To, int From = 1>
struct printer {
static void print() {
cout << From << endl;
printer<To, From + 1>::print();
}
};
template <int Done>
struct printer<Done, Done> {
static void print() {
cout << Done << endl;
}
};
int main()
{
printer<1000>::print();
}
其他回答
立足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
也许这太明显和容易遵循,但这是标准c++,不转储堆栈和运行在O(n)时间使用O(n)内存。
#include <iostream>
#include <vector>
using namespace std;
int main (int argc, char** args) {
vector<int> foo = vector<int>(1000);
int terminator = 0;
p:
cout << terminator << endl;
try {
foo.at(terminator++);
} catch(...) {
return 0;
}
goto p;
}
将1到1000放入文件file中
int main()
{
system("cat file");
return 0;
}
我想知道面试官是不是说错了一个问题:不使用循环,计算从1到1000(或从n到m的任意数字)的和。它还教会我们如何分析问题。在C中从1到1000s打印#s总是依赖于在生产程序中可能不会使用的技巧(Main中的尾部递归,计算真实性的副作用,或预处理和模板技巧)。
这将是一个很好的抽查,看看你是否接受过数学训练,因为关于高斯和他的解的古老故事可能对任何接受过数学训练的人都很熟悉。
system("/usr/bin/env echo {1..1000}");