我对编程很陌生,我只学习了C语言的基础知识。我决定解决哈佛CS50课程中的这个问题。请检查我的密码。
我们必须编写一个程序,从用户那里获取一个高度,并打印出这个高度的金字塔。
如果用户在提示下输入8,程序将如何工作:
$ ./mario
Height: 8
# #
## ##
### ###
#### ####
##### #####
###### ######
####### #######
######## ########我的代码:
#include <stdio.h>
void pattern(int n, int temp); // function prototype
int main()
{
int height, same_as; // same_as is just a temporary variable
printf("Enter the height \n");
while (1)
{
scanf("%d", &height);
if (height >= 1 && height <= 8) // if height is between 1 and 8
break;
else
printf("Height = %d\n", height);
}
same_as = height;
printf("Height = %d\n", height);
pattern(height, same_as);
return 0;
}
// definition of the function
void pattern(int n, int temp)
{
int i; // i is the counter
// printing the first line
if (n == 1)
{
for (i = 0; i != 2 * temp + 1; i++)
{
if (i == temp - 1 || i == temp + 1)
{
printf("#");
}
else if (i == temp)
{
printf(" ");
}
else if (i > temp + 1)
break;
else
printf(" ");
}
printf("\n");
return;
}
else
{
pattern(n - 1, temp);
// for loop to print each line
for (i = 0; i != 2 * temp + 1; i++)
{
// all the places where we print # in the same line
if (i >= temp - n && i <= temp + n && i != temp) // very important
{
printf("#");
}
else if (i == temp)
{
printf(" ");
}
else if (i > temp + n)
break;
else
printf(" ");
}
printf("\n");
}
}发布于 2022-01-20 14:38:32
当您使用scanf()时,在使用您要分配给它的任何值之前,检查它的返回值非常重要。
例如,尝试输入一个非数字:它将不断循环,重新尝试解析无效的输入。
如果输入不能被解析,那么最好放弃,当然在C职业生涯的这个阶段(非常健壮的输入处理是一个高级主题)。
if (scanf("%d", &height) != 1) {
fputs("Sorry, I didn't understand you.\n", stderr);
return EXIT_FAILURE;
}注意:我们需要包含<stdlib.h>来定义返回值。
额外的变量same_as是不必要的:
pattern(height, height);还不清楚temp参数的作用是什么:
空模式( int n,int temp)
它真的需要一个更好的名字。
(部分回顾-我可能会有时间回到这里)
https://codereview.stackexchange.com/questions/273181
复制相似问题