用c++创建一个权力表

Creating a Table of Powers with C++

本文关键字:一个 c++ 创建      更新时间:2023-10-16

我正在做一个项目,使用嵌套的for循环打印出指数表。用户指定要打印的行数和功率数。例如,如果用户指定2行和3次幂,程序应该打印1,1,1和2,4,9(2^1,2,3等)。我应该注意到这是类的,我们不允许使用cmath,否则我会使用pow()。我似乎不能在一个嵌套的for循环中找出正确的函数,它可以同时改变基数和指数的值。这是我目前所知道的。谢谢你的帮助!

#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
    int r, p, a;
    cout << "The program prints a table of exponential powers.nEnter the number of rows to print: ";
    cin >> r;
    cout << "Enter the number of powers to print: " ;
    cin >> p;
    cout << endl;
    for (int i = 1 ; i <= r; i++)
    {
        cout << setw(2) << i;       
        for (int q = 1; q <= i; q++)
        {
            a = (q * q); //This only works for static numbers...
            cout << setw(8) << a;
        }
        cout << endl;
    }
}
for (int i = 1 ; i <= r; i++)
{
    cout << setw(2) << i;
    int a = 1;
    for (int q = 1; q <= r; q++)
    {
        a = (a * i);
        cout << setw(8) << a;
    }
    cout << endl;
}

有几点需要注意。首先,您可以通过保持变量a并将每个幂乘以i来计算幂。另外,我认为你应该让第二个循环的上界是r而不是I

您需要更改几次幂的累加方式。

还有,你在for循环中使用了错误的变量来结束循环。

#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
   int r, p, a;
   cout << "The program prints a table of exponential powers.nEnter the number of rows to print: ";
   cin >> r;
   cout << "Enter the number of powers to print: " ;
   cin >> p;
   cout << endl;
   for (int i = 1 ; i <= r; i++)
   {
      cout << setw(2) << i;       
      a = 1;   // Start with 1
      for (int q = 1; q <= p; q++) // That needs to <= p, not <= i
      {
         a *= i; // Multiply it by i get the value of i^q
         cout << setw(8) << a;
      }
      cout << endl;
   }
}