没有初始化变量的C++
C++ Without initialization variable
我从朋友那里遇到了一个问题。问题是在没有初始化变量的情况下,如何打印0到10?
我知道使用初始化进行循环打印的方法
for(int i=0;i<=10;i++) {
cout<<i;
}
此处int i = 0
已初始化。那么,在不初始化相关变量的情况下,如何打印0到10个值呢?有没有可能?
你的朋友应该学会更精确地指定他们的问题。
int i; // i is not initialized
i = 0; // i is assigned
for( ;i<=10;i++)
{
cout<<i;
}
保持简单:
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>();
使用模板元编程可以实现最简单的解决方案:
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);
#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;
}
看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;
}
malloc、递归、模板怎么样。或者使用直接访问(长)0x12ff7b=1;(长)0x12ff7b=(长)0x12ff7b+1;只要(long)0x12ff7b在可写存储器中。这真的是一个悬而未决的问题
其他一些答案似乎认为我们可以使用参数初始化(或赋值)。我认为这是作弊,但如果允许的话,我会提交这个更简单的版本:
void f(int n){
for(; n <= 10; ++n)
cout << n;
}
int main() {
f(0);
}
int I=0;
while (I!=11) {
cout<< I; I++;
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 执行函数时导致崩溃的变量
- 变量没有改变?通过向量的函数调用