[英]Making Pyramid in C++ Using functions & loops in program
当我将循环分开时,这是有道理的,但是当我将它组合起来时,我似乎无法正确创建金字塔。 这是一个逻辑错误。 我不确定另一个循环中的循环是否没有正确完成。 高度是要在金字塔中显示的行数。
#include <iostream>
using namespace std;
/********** DO NOT ALTER THIS CODE **********/
void printStar(int numStars){
int i;
for (i=1; i<=numStars; i = i+1)
cout<<"*";
}
void printSpace(int numSpaces){
int i;
for (i=1; i<=numSpaces; i = i+1)
cout<<" ";
}
/********** WRITE YOU CODE IN THE main **********/
int main(){
int count, heigh,p;
cout<<"Please enter height"<<endl;
cin>>heigh;
for(count= heigh; count>=0; count= count-1) {
printSpace(count);
for(p= 1; p<=(heigh*2); p=p+2) {
printStar(p);
}
cout<<endl;
}
return 0;
}
我们初学者应该互相帮助。:)
这个给你。
#include <iostream>
using namespace std;
/********** DO NOT ALTER THIS CODE **********/
void printStar(int numStars){
int i;
for (i=1; i<=numStars; i = i+1)
cout<<"*";
}
void printSpace(int numSpaces){
int i;
for (i=1; i<=numSpaces; i = i+1)
cout<<" ";
}
/********** WRITE YOU CODE IN THE main **********/
int main()
{
while ( true )
{
std::cout << "Enter a non-negative height of the pyramid (0 - exit): ";
int height;
if ( not ( std::cin >> height ) or ( height <= 0 ) ) break;
std::cout << '\n';
for ( int i = 0; i < height; i++ )
{
printSpace( height - i - 1 );
printStar( 2 * i + 1 );
std::cout << '\n';
}
std::cout << '\n';
}
return 0;
}
程序输出看起来像
Enter a non-negative height of the pyramid (0 - exit): 10
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
Enter a non-negative height of the pyramid (0 - exit): 5
*
***
*****
*******
*********
Enter a non-negative height of the pyramid (0 - exit): 0
考虑到在你的程序中这个循环
for(count= heigh; count>=0; count= count-1) {
有heigh + 1
次迭代,而不是heigh
迭代。 而这个循环
for(p= 1; p<=(heigh*2); p=p+2) {
printStar(p);
}
在外循环内没有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.