在最近的一次采访中,我被问到一个非常奇怪的问题。面试官问我如何仅使用编译器功能计算 1+2+3+...+1000。这意味着我不能编写程序并执行它,但我应该只编写一个程序,它可以驱动编译器在编译时计算这个总和,并在编译完成时打印结果。作为提示,他告诉我我可以使用编译器的泛型和预处理器特性。可以使用 C++、C# 或 Java 编译器。有什么想法???
这个问题与在没有任何循环 asked here 的情况下计算总和无关。此外,需要注意的是,总和应该在编译期间计算。使用 C++ 编译器指令仅打印结果是 Not Acceptable 。
阅读有关已发布答案的更多信息,我发现使用 C++ 模板在编译期间解决问题称为元编程。这是 Erwin Unruh 博士在标准化 C++ 语言的过程中偶然发现的一种技术。您可以在 wiki page of meta-programming 上阅读有关此主题的更多信息。 似乎可以使用 Java 注释在 Java 中编写程序。您可以看看下面的 maress's 答案。
this one 是一本关于 C++ 元编程的好书。有兴趣的值得一看。
Boost 的 MPL this link 是一个有用的 C++ 元编程库。
最佳答案
更新现在提高了递归深度!适用于 MSVC10 和 GCC,无需增加深度。 :)
简单的编译时递归+加法:
template<unsigned Cur, unsigned Goal>
struct adder{
static unsigned const sub_goal = (Cur + Goal) / 2;
static unsigned const tmp = adder<Cur, sub_goal>::value;
static unsigned const value = tmp + adder<sub_goal+1, Goal>::value;
};
template<unsigned Goal>
struct adder<Goal, Goal>{
static unsigned const value = Goal;
};
测试代码:
template<unsigned Start>
struct sum_from{
template<unsigned Goal>
struct to{
template<unsigned N>
struct equals;
typedef equals<adder<Start, Goal>::value> result;
};
};
int main(){
sum_from<1>::to<1000>::result();
}
GCC 的输出:
error: declaration of ‘struct sum_from<1u>::to<1000u>::equals<500500u>’
MSVC10 的输出:
error C2514: 'sum_from<Start>::to<Goal>::equals<Result>' : class has no constructors
with
[
Start=1,
Goal=1000,
Result=500500
]
关于c# - 如何在编译时驱动 C#、C++ 或 Java 编译器计算 1+2+3+...+1000?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8763497/