C ++ Diamond控制台输出问题

时间:2013-02-20 21:32:21

标签: c++ for-loop visual-c++ cin

我正在尝试让我的for循环输出一个给定用户特定最大值和最小值的菱形,不允许偶数输入。任何想法,将不胜感激。实践并不像我想象的那样顺利。

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{

int rows, count;

cout<<"What is the width of the diamond (3 to 21, odd values only): ";
cin>>rows;

//Error checking
if(rows < 1 || rows > 25)
    {
        cout<<"Invalid. please enter an odd number from 1 to 25: ";
        cin>>rows;
    }

//Ascending
for (count = 1; count < rows; count += 1)       
    {
        for (int rows = 0; rows < count; rows ++)
        cout<<"*";
        cout<<endl;
    }

//Descending
for (count; count > 0; count -= 1)              
    {
        for (int rows = 0; rows < count; rows ++)
        cout<<"*";
        cout<<endl;
    }


cin.get();
cin.get();

return 0;

}

1 个答案:

答案 0 :(得分:1)

执行目标的前半部分 - :

for (int stars = 1; stars <= rows; stars+=2)
{
        int padding = rows - stars;
        for (int c = 0; c < padding/2; ++c)
           cout<<" ";
        for (int s = 0; s < stars; ++s)
           cout<<"*";
        cout<<endl;
}