繁体   English   中英

C ++没有初始化变量

[英]C++ Without initialization variable

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

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

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

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

把事情简单化:

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>();

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

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

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

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);

看看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;
}

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

int i;
i ^= i; // this effectively sets i to zero
for (; i <= 10; i++) {
    cout << i;
}
#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;
}
#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;
}

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM