【发布时间】:2020-08-03 05:47:31
【问题描述】:
我尝试使用 nRows 打印钻石。 第一个程序有效,但是当我按照以下说明将其分解为功能时: GetNRows(无效); DrawShape(int nRows); numberSpaces( int nRows, int row ); numberStars( int nRows, int row ); PrintChars(int n, char ch); 我不知道如何将值传递给函数并在每次传入时更新值。 请看我的代码。
#include <iostream>
using namespace std;
int getNRows(int &);
int calcNumSpace( int nRows, int row );
int calcNumStars( int nRows, int row );
void printChars( int n, char ch );
void drawShape( int nRows );
int main()
{
int nRows;
getNRows( nRows );
drawShape( nRows );
return 0;
}
int getNRows(int &nRows)
{
do
{
cout << "Enter number of rows (3-23) :";
cin >> nRows;
}while ( nRows > 23 || nRows < 3);
if ( nRows % 2 == 0)
{
nRows += 1;
}
return nRows;
}
void drawShape( int nRows )
{
int n, row;
for( row = 0; row < nRows; row++ )
{
n = calcNumSpace( nRows, row );
printChars( n, ' ' );
n = calcNumStars(nRows, row );
printChars( n, '*' );
cout << endl;
}
}
int calcNumSpace( int nRows, int row )
{
int space;
!!! What shoud I do here to update space every time row increase 1 ???
return space;
}
int calcNumStars( int nRows, int row )
{
int stars;
same for space above!!!
return stars;
}
void printChars( int n, char ch )
{
int i;
for(i = 0; i < n; i++)
{
cout << ch;
}
}
例如:
Enter number of rows (3-23) :5
*
***
*****
***
*
Program ended with exit code: 0
这是我的第一个程序:
#include <iostream>
using namespace std;
int main()
{
int n, i=0 , j=0, k=0, space, stars;
do
{
cout << "Enter number of rows (3-23) :";
cin >> n;
}while ( n > 23 || n < 3);
if ( n % 2 == 0)
{
n += 1;
}
// print top half
space = n / 2;
stars = 1;
for( i = 0; i < n / 2 + 1; i++ )
{
for( j = 0; j < space; j++ )
{
cout << " ";
}
for( k = 0; k < stars; k++)
{
cout << "*";
}
cout << endl;
stars = stars + 2;
space = space - 1;
}
// print bottom half
space = 1;
stars = n - 2;
for( i = 0; i < n / 2; i++)
{
for( j = 0; j < space; j++)
{
cout << " ";
}
for( k = 0; k < stars; k++)
{
cout << "*";
}
cout << endl;
space = space + 1;
stars = stars - 2;
}
return 0;
}
【问题讨论】:
-
您说“第一个程序有效”。所以这意味着你必须在之前完成
CalcNumSpace和calcNumStars的计算,即使你说你不能在这个程序中做同样的计算。我猜你没有正确理解函数是如何工作的。例如,您说“每次行增加 1 时我应该在这里做什么来更新空间”,但这是不对的。您无需更新任何内容,您必须计算每行的空格数。 -
在给定行数和总行数的情况下,计算出一行空格数的公式。你必须在你的第一个程序中已经有了这个公式,所以你所要做的就是把它复制到这里。如果您仍然被卡住,那么尝试一下,尝试一些不同的公式,看看它们对产生的形状有什么影响。最后,如果你真的被卡住了,那么写下你最好尝试在这里发布并询问它有什么问题。人们喜欢看到你所做的努力。