gpt4 book ai didi

c - HackerRank 阶梯 C 困惑

转载 作者:行者123 更新时间:2023-11-30 16:44:55 35 4
gpt4 key购买 nike

嗨,我是个新手,正在尝试通过 hackerrank 来提高,我正在进行楼梯练习 staircase excercise

但是我的输出与问题不同,因为我的楼梯似乎在结果前面有一个额外的空间,从而使其不正确。这是我的代码。

#include <stdio.h>

int main ()
{

int size = 0;

//input size of staircase
scanf("%d" , &size);


//create array to hold staircase
char list [size];
//iterate through and fill up array with spaces
for (int i = 0; i <size; ++i)
{
list[i] = ' ';
}
//the iterate backwards -1 each time replacing each spcae with a '#' and printing each stair case starting from smallest at the top.
for (int i = size; i >0; i--)
{
list[i] = '#';
printf("%s\n", list);
}


return 0;
}

我很困惑到底是什么问题以及为什么我的楼梯比预期的问题更间隔?我一直在努力解决这个问题,确实非常需要任何帮助。

我的输出:

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

*编辑 - 感谢您的帮助,所有答案都有帮助。

最佳答案

有几个错误:

1) 您忘记在字符串末尾添加空字符 ('\0')。这样做:

for (int i = 0; i <size; ++i)
{
list[i] = ' ';
}
list[i] ='\0';

2)

for (int i = size; i >0; i--)
{
list[i] = '#';
printf("%s\n", list);
}

此处您尝试访问的字符串索引无效(当 i=size 时)。这样做:

for (int i = size-1; i > -1; i--)
{
list[i] = '#';
printf("%s\n", list);
}

关于c - HackerRank 阶梯 C 困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44318058/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com