用set base/exponent为指数嵌套for循环

C++ Nested for loop for exponents with set base/exponent

本文关键字:指数 嵌套 for 循环 exponent set base      更新时间:2023-10-16

所以我需要一些帮助。我想打印出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;

使用<<运算符会简单得多。

因为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;
}