任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
也许这太明显和容易遵循,但这是标准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;
}
其他回答
#include <stdio.h>
int main() { printf("numbers from 1 to 1000"); return 0; }
这就像另一个以“愤怒”结尾的英语单词谜语,对吧?
简单C版本,在1000处终止:
int print_stuff(int count) {
printf("%d\n", count);
return (count ^ 1000) && print_stuff(count+1);
}
int main(int argc, char *argv[]) {
print_stuff(1);
return 0;
}
经过一些修改,我想出了这个:
template<int n>
class Printer
{
public:
Printer()
{
std::cout << (n + 1) << std::endl;
mNextPrinter.reset(new NextPrinter);
}
private:
typedef Printer<n + 1> NextPrinter;
std::auto_ptr<NextPrinter> mNextPrinter;
};
template<>
class Printer<1000>
{
};
int main()
{
Printer<0> p;
return 0;
}
后来@ybungalobill的作品启发我想出了这个更简单的版本:
struct NumberPrinter
{
NumberPrinter()
{
static int fNumber = 1;
std::cout << fNumber++ << std::endl;
}
};
int main()
{
NumberPrinter n[1000];
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
#define N 10 //10 or 1000, doesn't matter
class A{
public:
A(){
//cout << "A(): " << m_ << endl; //uncomment to show the difference between gcc and Microsoft C++ compiler
}
A(const A&){
++m_;
cout << m_ << endl;
}
private:
static int m_; //global counter
};
int A::m_(0); //initialization
int main(int argc, char* argv[])
{
//Creates a vector with N elements. Printing is from the copy constructor,
//which is called exactly N times.
vector<A> v(N);
return 0;
}
实现注意: 使用gcc:默认构造函数创建一个“master”元素。 然后元素被复制构造函数复制N次。 在微软c++编译器中:所有元素都是由默认构造函数创建的 然后被复制构造函数复制。
static void Main(string[] args)
{
print(1000);
System.Console.ReadKey();
}
static bool print(int val)
{
try
{
print( ((val/val)*val) - 1);
System.Console.WriteLine(val.ToString());
}
catch (Exception ex)
{
return false;
}
return true;
}