2010-03-04 92 views
0

我正在嘗試使用用戶輸入的選項創建一個梯形。我知道我的代碼可能不是最好的方式,但迄今爲止它的工作原理!我的問題是我需要梯形的底部觸摸輸出窗口的左側。我究竟做錯了什麼?使用用戶輸入的字符創建梯形。 (控制檯應用程序)

#include <iostream> 
#include <iomanip> 
#include <cmath> 

using namespace std; 

int main() 
{ 
    int topw, height, width, rowCount = 0, temp; 
    char fill; 

    cout << "Please type in the top width: "; 
    cin >> topw; 

    cout << "Please type in the height: "; 
    cin >> height; 

    cout << "Please type in the character: "; 
    cin >> fill; 

    width = topw + (2 * (height - 1)); 
    cout<<setw(width); 

    for(int i = 0; i < topw;i++) 
    { 
     cout << fill; 
    } 
    cout << endl; 
    rowCount++; 
    width--; 

    temp = topw + 1; 

    while(rowCount < height) 
    { 
     cout<<setw(width); 

     for(int i = 0; i <= temp; i++) 
     { 
      cout << fill; 
     } 
     cout << endl; 

     rowCount++; 
     width--; 
     temp = temp +2; 
    } 
} 
+0

這是功課? – Xorlev 2010-03-04 06:39:59

+0

「最好的梯形」是什麼意思? – 2010-03-04 06:56:59

回答

1

setw設置下一個操作的寬度,而不是整條線。因此,單個cout的寬度填充設置爲該值。這是給你的填充,但你需要爲最後一行設置setw爲0。

也,似乎有一些多餘的代碼試試:

int main() 
{ 
int topw, height, width, rowCount = 0, temp; 
char fill; 

cout << "Please type in the top width: "; 
cin >> topw; 

cout << "Please type in the height: "; 
cin >> height; 

cout << "Please type in the character: "; 
cin >> fill; 

width = height; 
cout<<setw(width); 

temp = topw; 

while(rowCount < height) 
{ 
    cout<<setw(width); 

    for(int i = 0; i < temp; i++) 
    { 
     cout << fill; 
    } 
    cout << endl; 

    rowCount++; 
    width--; 
    temp = temp +2; 
} 
} 
相關問題