在在这里问这个问题之前我想了很久,但我现在花了太多时间试图在不作弊的情况下解决这个问题。 CS50 mario ps1(不太舒服)要求*简单的左对齐(首先)金字塔,但我的代码给了我它颠倒,我不明白为什么。
#include <cs50.h>
#include <stdio.h>
int main (void)
{
int n;
do
{
n = get_int("Pyramid Height: ");
}
while (n < 1 || n > 8);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i ; j++)
printf("#");
for (int j = 0; j < n - i; j++)
{
printf(" ");
}
printf("\n");
}
}
如果此类问题经常出现,我很抱歉,但我确实需要您的帮助。 预先感谢。
编辑:
........#
.......##
......###
.....####
....#####
...######
..#######
.########
我可以稍后将点更改为空格,这只是为了可视化;
高度限制是8,所以我猜每行总是八个字符;
我实际上添加了尾随空格,以便金字塔可以右对齐,我之前提到过错误;
我要查看如何调试小程序?;
抱歉,我是新手,我不知道这里和堆栈交换之间有区别,会研究一下。
*抱歉“meh”英语,这不是我的母语。
看看我的代码和你的代码有什么区别(尤其是如何计数):
void draw(int n, int align, int dir)
{
for (int i = 1; i <= n; i++)
{
if(align)
{
for(int s = 0; s < (dir ? (n - i) : i - 1); s++)
{
printf(" ");
}
}
for (int j = 0; j < (dir ? i : (n - i + 1)) ; j++)
{
printf("#");
}
printf("\n");
}
}
int main (void)
{
draw(8,1,0);
printf("\n");
draw(8,1,1);
printf("\n");
draw(8,0,0);
printf("\n");
draw(8,0,1);
}
我的代码给了我它颠倒,我不明白为什么
让我们看看代码是什么样的
// There's a loop executed n times. The body prints a line, so n lines are printed.
// In case you have doubts, the characters are normally printed top to bottom and
// left to right.
for (int i = 0; i < n; i++)
{
// The following loop prints (n - i) characters '#' at the beginning
// of each line. That's NOT what you are supposed to do, kind the opposite.
for (int j = 0; j < n - i ; j++)
printf("#");
// You should first print the spaces, then the '#'s, starting from 1 '#' at
// the first line and increasing the number by one at each line (so you have
// to change the condition in the loop accordingly).
// This loop prints the right amount of spaces, but only after
// all the '#'s and just before the end of the line, so that you just
// can't see them (change the printed char to '.' to visualize those).
for (int j = 0; j < n - i; j++)
{
printf(" ");
}
// Note that you could use putchar('\n'), here and previously, to print
// only one char, instead of using printf() to print string literals.
printf("\n");
}
这里是CS50这个问题的高级版本。它包含您问题的答案,也是解决方案的一部分。我强烈建议你看一下这个,不要复制粘贴它,而是尝试自己写下来。
#include <cs50.h>
#include <stdio.h>
int main(void){
int pyramidHeight;
do {
pyramidHeight = get_int("Please provide puramid height..: ");
}
while (pyramidHeight < 1 || pyramidHeight > 8);
// looping over the left side of the pyramid
for (int i = 0; i < pyramidHeight; i++){
int count = i+1;
int spaces = pyramidHeight-(i+1);
//first empty spaces to the left
for(int h = 0; h < spaces; h++){
printf(" ");
}
//then hashes
for (int j = 0; j < count; j++){
printf("#");
}
//space between pyramid hashes
printf(" ");
// hashes to the right of hte pyramid
for (int k = 0; k < count; k++){
printf("#");
}
// spaces to the right of the pyramid
for(int f = 0; f < spaces; f++){
printf(" ");
}
printf("\n");
}
}