将 1 居中放在顶部

center the 1 at the top

本文关键字:顶部      更新时间:2023-10-16
#include <iostream> 
using namespace std;
int main()
{
int rows, count, num, space;//creating four variables to use for the loops
cout << "Enter number of rows: ";//prompting the user to input the number of rows
cin >> rows;
while (rows < 1 || rows>9)
{
cout << "Entry must be between 1 and 9. Please Re-enter the number of rows" << endl; //Asking the user to re-enter the number of rows if it was an invalid input
cin >> rows;
}
for (count = 1; count <= rows; count++) //for function that loops from 1-how many rows the user puts in
{
for (space= 1; space < rows; space++) //inner loop that loops from 1 to how many rows the user put in and outputs a space
{
cout << "  ";
}
for (num = 1; num <= (2*count-1); num++)//the last row of the pyramid has one less than two time sthe number the user input so this loops unitl that is hit
{
cout <<count << " ";
}
cout << "n"; //outputs a new line 
}
system("pause");
return 0;
}

查看代码,您正在制作一个数字的直角三角形,并猜测您需要一个等腰数字金字塔 请参考以下代码:

#include <iostream>
#include <string>
bool makeIsoscelesPyramid(const unsigned int& size)
{
if( size > 9 )
{
std::cout<<"Please Enter a positive number less than 9"<<std::endl;
return false;
}
for (int i = 0; i < size; i++)
{
//Number of Space to input
auto nSpace = size - ( i );
std::cout << std::string( nSpace, ' ');
//Times the number is repeated 1, 3, 5 ...
auto nTimesNumber = (i * 2) + 1;
//'1'+i could only print till 9 
std::cout << std::string( nTimesNumber, '1'+i) << std::endl;
}
return true;
}
int main()
{
unsigned int nRows = 0;
bool bReturn = false;
do
{
std::cout << "Enter number of rows: t";
std::cin>>nRows;
std::cout<<std::endl;
bReturn =  makeIsoscelesPyramid(nRows);
} while( !bReturn );
return 0;
}

输出:

Enter number of rows:   5
1
222
33333
4444444
555555555