C ++嵌套for循环用于具有set base / exponent的指数

时间:2016-10-30 22:03:17

标签: c++ for-loop nested-loops exponent

所以我需要一些帮助。我想打印出2和2 ^ 20之间的整数2的整数幂的整数。我想我每次需要增加1的幂,但我似乎无法弄清楚内部for循环内部的内容。我不能使用pow()函数

c = 2;    
cout << "\nPROBLEM C" << endl;
for (int powerC = 1; powerC <= 20; powerC++) // powerC is exponent
{ 
  cout << setw(5) << powerC << " ";
  counterC++;
  for (int x = 1; x <= 20; x++) // where I am having trouble with
  {
     c = (c*powerC);
     cout << setw(5) << c;
  } // end inner for loop
    if (counterC % 8 == 0)
    {
        cout << endl;
    }
}
cout << "\nNumber of numbers = " << counterC;

1 个答案:

答案 0 :(得分:0)

使用<<运算符可以更加简单。

由于2是2 ^ 1,你想打印所有2 ^ 1到2 ^ 20的整数,或者20个数字:

int c = 2;
for (int i=0; i<20; i++)
{
    std::cout << c << std::endl;

    c <<= 1;
}