问题
Exercise: make a program that reads a natural number n and draws a pyramid of asterisks. Model for n = 5:
*
***
*****
*******
*********
Code:
int main ()
{
int n, i, j=1, aux1, aux2;
int spaces=1;
scanf ("%d", &n);
for (i=0; i<n; i++)
{
spaces += 1;
}
printf ("\n");
for (i=0; i<n; i++)
{
aux1 = j;
aux2 = spaces;
while (aux2 >= 1)
{
printf (" ");
aux2--;
}
while (aux1 >= 1)
{
printf ("*");
aux1--;
}
j += 2;
spaces--;
printf ("\n");
}
return 0;
}
My code is receiving "Presentation Error" from online judge because the last asterisks of every line have a space after. Any tips on how to fix it?
回答1:
Your code has spaces at the start of each line, not the end.
Here is the simplest way I can think of to go about solving that problem:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, j, height;
scanf("%d", &height);
for (i = 0; i < height; i++) {
for (j = 0; j < height - i - 1; j++)
putchar(' ');
for (; j < height + i; j++)
putchar('*');
putchar('\n');
}
return EXIT_SUCCESS;
}
回答2:
I'm pretty sure it's not including a space after the asterisks, and it's easy enough to see this for yourself. Near the bottom where you included the newline after the stars, I added an endmarker (|) just so we can see: is there a space?
I don't see one.
#include <stdio.h>
int main ()
{
int n;
scanf ("%d", &n);
int spaces_before_stars = n - 1;
printf ("\n");
int i, nstars;
for (i = 0, nstars = 1; i<n; i++)
{
int aux1 = nstars;
int aux2 = spaces_before_stars;
while (aux2-- > 0)
printf (" ");
while (aux1-- > 0)
printf("*");
nstars += 2;
spaces_before_stars--;
printf ("|\n"); // the "|" marks the end of the line, remove for final
}
return 0;
}
However your version of the code had spaces at the start of each line, which is probably what the presentation code is unhappy with.
Refactoring the code a bit with better variable names makes it easier to follow - you should see no extra leading spaces and no trailing spaces.
回答3:
Given n>0, this should do the trick, assuming alternating blank lines is desired and a trailing extraneous new line allowed.
char *ast = malloc(n * 2);
if (ast == NULL)
return(1);
memset(ast, '*', n*2);
ast[(n*2)-1] = 0;
for (i=1; i<=n; i++) {
int spaces = n - i;
printf("%*s%.*s\n\n", spaces, "", (i*2)-1, ast);
}
free(ast);
return (0);
来源:https://stackoverflow.com/questions/59709181/asterisk-pyramid-in-c