开发者

c++ / c# pyramid scheme how to make it? [closed]

开发者_Python百科 It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I am looking for a c++ or c# code for a pyramid scheme (i level: x, second level x x...and so on). thx


Here is some pseudo-code that you can to translate into any imperative language of your choice:

for each i from 1 to max
    for each k from 1 to i
        print x
    newline


It sounds like you want this formatted a little bit. It also sounds like this is a high school, beginning of semester assignment, and you may be cheating yourself out of discovering whatever language you're using. But let's say you're not, and you want formatting.

FredOverflow gives the right pseudocode algo for printing:

x
xx
xxx
...

but if you want it to be centered then you need to consider how many spaces to add first.

If your pyramid is n tall, then the bottom is n wide. Row n-1 contains n-1 x's, but needs even spacing, and you can't just add 0.5 spaces to each side, at least with text (unless this is in a GUI and you're using some DrawText(x,y,text) method). Instead, consider that if you put a space between each x, you'll always have an odd # of characters on a line, allowing pyramidal spacing, like so:

  x
 x x
x x x

Thus you can do:

for (i = 1; i<= n; i++) {
  for (j = 0; j < n-i; j++) {
    printf(" ");
  }
  for (k = 0; k < i; i++) {
    printf("x ");
  }
  printf("\n");
}

Or rewrite to suit your needs / be more efficient. There are options here, and you should try doing it another way to see what the differences teach you. Specifically, though, pay attention to the math used in your recursion loops. It's easy, especially when starting out, to have off-by-1 math errors in loops. Heck, I hope I didn't make one just now!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜