c语言 - 函数无限循环 - do/while 函数



目标:

实现一个程序,打印出指定高度的双半金字塔,如下所示。

$ ./mario
Height: 4
#  #
##  ##
###  ###
####  ####

问题:

在过去的 3 个小时左右一直在弄乱代码。我让第一行工作,但除此之外的所有内容都只是 2 个由单个哈希标记组成的平行支柱。目前,该程序正在无限期地打印哈希标记。

法典:

int main (void) {
// user gives height value for pyramid
// h = height
int h;
do {
printf (
"How tall do you want your pyramid to be? Please type a number "
"between 0 and 23.n");
h = get_int ();
} while (h < 0 || h > 23);
// Left side of pyramid says spaces first, followed by hashes. Two spaces
// inbetween sides of the pyramid. Right side renders hashes first, then
// inputs newline character.
// r = row
// s = space
// p = hash
// q = hash right
int q;
int p;
int s;
int r;
for (r = 0; r < h; r++) {
do {
do {
printf (" ");
s++;
} while (s < h - r);
// says spaces
do {
printf ("#");
p++;
} while (p < r++);
// says left hashes
// always print 2 spaces inbetween
printf ("  "); // two spaces
do {
printf ("#");
q++;
} while (q < r++);
// says right hashes
printf ("n");
q = 0;
p = 0;
s = 0;
// reset q,p,s values
} // end bracket of encompassing 'do' function
while (r < h);
//'for' function should execute once, increment 'r' by 1, and repeat
//until row height becomes height provided by user.
} // end bracket of for loop
} // end bracket of int main

预期成果:

程序创建由哈希符号和空格形成的金字塔。

实际结果:

无限循环打印功能。

循环的结尾是这样的:

p++;
}
while (p < r++);

因此,r总是领先于p,因为您正在增加两者。这就是你的无限循环。

在第二个while内部循环之后移动r++我得到了一个很好的结果,如下所示:

#  #
#  #
##  ##
###  ###

所以仍然有点调整,你在这里。另一个问题是do/while即使条件为假,也会执行一次。用while循环替换,否则你就像上面一样

do
{
while (s < h - r)
{
printf(" ");
s++;
}
//says spaces
while (p < r)
{
printf("#");
p++;
}
//says left hashes
//always print 2 spaces inbetween
printf("  ");
//two spaces
while(q < r)
{
printf("#");
q++;
}
//says right hashes
r++;
printf("n");
q = 0;
p = 0;
s = 0;
// reset q,p,s values
}//end bracket of encompassing 'do' function
while(r < h);

请注意,使用"Notepad++/TextFX/TextFX edit/Reindent C++ code"自动缩进代码也很便宜

#  #
##  ##
###  ###
####  ####
#####  #####
######  ######
#######  #######
########  ########
#########  #########

一个更短的实现,用于您的研究

int i,j;
for (i=0 ; i<h ; i++) {            // h lines
for(j=0 ; j < h+2+i+1 ; j++) { // cover all characters on 1 line
printf("%s", j<h-i-1 || j<h+2 && j>=h ? " " : "#");
}
printf("n");                  // end of line
}

关于j<h-i-1 || j<h+2 && j>=h ? " " : "#"

  • 在第一个#之前j<h-i-1空格
  • #之间的j<h+2 && j>=h空格
  • ?:运算符:C ? A : B转换为如果 C 为真,则给出 A 否则给出 B

最新更新