2015-10-07 30 views
1

我正在使用嵌套的for-loops打印出一個指數數字表的項目。用戶指定要打印的行數和功率數量。例如,如果用戶指定2行和3個權力,程序應該打印1,1,1和2,4,9(2^1,2,3等)。我應該注意到這是針對課堂的,我們不允許使用cmath,否則我會使用pow()。我似乎無法找出嵌套for循環中的正確函數,它可以更改基本值和指數值。這是迄今爲止我所擁有的。謝謝你的幫助!使用C++創建權力表

#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; 
    } 
} 
+3

您的預期模式,第一行中的'1 1 1'和第二行中的'2 4 9'沒有意義。第二行中是否指「2 4 8」? '2^1 2^2 2^3'? –

+0

嘗試更簡單的方法:打印*一行*長度可變的程序。提示:不要單獨計算每個功率。 – Beta

+0

[工作代碼](http://coliru.stacked-crooked.com/a/57e7a0eaf621bb08)。 –

回答

0
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。

0

你需要夫婦改變方式積累價值提高數量的權力。

另外,您正在使用錯誤的變量來結束內部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; 
    } 
}