C ++没有初始化变量

时间:2012-03-05 14:21:47

标签: c++ logic

我的朋友们遇到了问题。问题是没有初始化变量如何打印0到10?

我知道使用初始化使用for循环打印的方法

 for(int i=0;i<=10;i++) {
     cout<<i;
 }

此处int i = 0已初始化。那么如何在不初始化相关变量的情况下打印0到10个值?有可能吗?

10 个答案:

答案 0 :(得分:11)

保持简单:

cout << "0" << "1" << "2" << "3" << "4" << "5" << "6" << "7" << "8" << "9" << "10";
cout << "012345678910";

运行时递归:

void myPrint(int x)
{ 
    cout << x;
    if ( x < 10 )
       myPrint( x+1 );
}

myPrint(0);

编译时递归:

template<int x> void foo()
{ 
    foo<x-1>(); 
    cout << x << '\n'; 
}

template<> void foo<0>() 
{ 
    cout << 0 << '\n'; 
}

foo<10>();

答案 1 :(得分:11)

你的朋友应该学会更准确地指出他们的问题。

int i; // i is not initialized
i = 0; // i is assigned
for( ;i<=10;i++)
{
  cout<<i;
}

答案 2 :(得分:2)

使用模板元编程可以实现最简单的解决方案:

template<> void f<0>() { cout << 0; }
template<int I> void f() { f<I-1>(); cout << I; }
f<10>();

或者只使用递归的lambda函数。

function<void(int)> f = [&f] (int i) { i ? f(i-1) : (void)0; cout << i; };
f(10);

答案 3 :(得分:1)

#include <iostream>

template<int N>
struct printer {
  printer() {
    std::cout << N << std::endl;
    printer<N+1>();
  }
};

template<>
struct printer<10> {
  printer() {
    std::cout << 10 << std::endl;
  }
};

int main()  
{
  printer<0>();
  return 0;
}

答案 4 :(得分:1)

#include <iostream>
#include <vector>
#include <algorithm>

int printAndAdd(int total, int next)
{
    std::cout << total;
    return total + next;
}

int main()
{
    std::vector<int> elevenOnes(11, 1);
    std::accumulate(elevenOnes.begin(), elevenOnes.end(), 0, printAndAdd);

    return 1;
}

答案 5 :(得分:1)

看看ma,没有常量(除了那个"%u"字符串文字,但不计算!!!

#include <cstdio> /* C code. C code run. Run code, run. */

/* umad? */
static unsigned long zero, ten, i;

int main(int argc, const char ** argv)
{
        /* setting ten to the right value... No initialization whatsoever! */
        ++ten;
        ten = ten << ten;
        ten = (ten << ten) + ten;
        /* then it's just a matter of printing out the values! */
        for (; i <= ten; ++i) {
                printf("%u", i);
        }
        /* As we all know, the Roman Empire (The unholy one, not the holy one,
           which wasn't holy, Roman, or an empire) fell since lacking any
           concept of zero, they couldn't indicate successful termination of
           their C programs. */
        return zero;
}

答案 6 :(得分:1)

使用XOR还有另一种解决方案 - 如果你XOR任何一个值,它将变为零。所以解决方案可能是:

int i;
i ^= i; // this effectively sets i to zero
for (; i <= 10; i++) {
    cout << i;
}

答案 7 :(得分:0)

怎么样的malloc,递归,模板。 或使用类似的东西直接访问 (长)0x12ff7b = 1; (长)0x12ff7b = (长)0x12ff7b +1; 只要(长)0x12ff7b在可写内存中。 这真的是一个开放式问题

答案 8 :(得分:0)

其他一些答案似乎假设我们可能使用参数初始化(或赋值)。我认为这是作弊,但如果允许,那么我提交这个更简单的版本:

void f(int n){
    for(; n <= 10; ++n)
         cout << n;
}

int main() {
    f(0);
}

答案 9 :(得分:-2)

int I=0;
while (I!=11) {
    cout<< I; I++;
}