简体   繁体   English

什么是我的 C 代码没有以楼梯模式打印#,这是来自hackerrank,我没有通过所有测试用例,但我无法指出原因?

[英]What is my C code not printing # in staircase pattern, this is from hackerrank, I did not pass all test cases, but i can't point out why?

Write a program that prints a staircase of size n.编写一个打印大小为 n 的楼梯的程序。

I did not pass through all the test cases and don't understand where I made mistake.我没有通过所有的测试用例,也不明白我在哪里犯了错误。

This is my code:这是我的代码:

void staircase(int n) {
    char a[n][n];
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            if((i + j) > ((n / 2) + 1)) {
                a[i][j] = '#';
                printf("%c", a[i][j]);
            } else {
                printf(" ");
            }
        }
        printf("\n");
    }
}

Given Input给定输入
6
Expected Output预计 Output

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

Explanation:解释:

The staircase is right-aligned, composed of # symbols and spaces, and has a height and width of n=6 .楼梯是右对齐的,由 # 符号和空格组成,高度和宽度为n=6

You do not need your a variable to do what you need.你不需要你a变量来做你需要的事情。 Here is a sample achieving what you want:这是一个实现您想要的示例:

void staircase(unsigned n)
{
        for (unsigned i = 0; i < n; ++i) {
                for (unsigned j = 0; j < (n - i - 1); ++j)
                        printf(" ");
                for (unsigned j = 0; j < (i + 1); ++j)
                        printf("#");
                printf("\n");
        }
}

The first loop is meant to cover every lines, then within it you make a loop which handles the spaces before the actual # symbols, and finally you make the loop handling the displaying of the symbols.第一个循环旨在覆盖每一行,然后在其中创建一个循环来处理实际#符号之前的空格,最后让循环处理符号的显示。

The problem is in the condition问题在于条件

if((i + j) > ((n / 2) + 1))

It should be它应该是

if(j >= n - i - 1)    // or   if(i + j >= n - 1)

To make this easier, I would create a helper function.为了使这更容易,我将创建一个助手 function。 Also, there's no need for the VLA a[n][n] that you don't even use for anything.此外,您甚至不需要用于任何事情的 VLA a[n][n]

void repeat_char(int x, char ch) {
    for(int i=0; i < x; ++i) putchar(ch);
}

void staircase(int n) {
    for(int i = 1; i <= n; ++i) {        
        repeat_char(n - i, ' ');   // or  printf("%*s", n - i, "");
        repeat_char(i, '#');
        putchar('\n');
    }
}

There is a much easier way of going about this than what you are trying to do:有一种比您尝试做的更简单的方法:

#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const int n = 6;
    char* str = malloc(sizeof(*str)*(n + 1));
    if (str == NULL) {
        printf("Somthing wrong with memory!\n");
        return 1;
    }
    memset(str, ' ', n);
    str[n] = '\0';
    for(int i = n - 1; i > -1; i--) {
        str[i] = '#';
        puts(str); //or maybe printf who cares
    }
    free(str);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM