我正在尝试制作一个循环,如果您愿意,可以制作一个楼梯或半个金字塔。 但是每当我打印它时,我所有的 # 字符都会被返回字符实心行的 $ 字符替换。
我在 (Int a) 循环中做错了什么。 我如何让它返回这样的东西:
#
##
###
####
#####
######
#######
########
而不是像这样的实心方块:
$$$$$$$$
$$$$$$$$
$$$$$$$$
$$$$$$$$
$$$$$$$$
$$$$$$$$
$$$$$$$$
$$$$$$$$
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void){
int ask = 0;
char line[9];
while ( ask < 1 || ask > 8 ) {
ask = get_int( "Height: ");
}
for (int i = 0 ; i < ask; i++)
{
for (int j = 0; j < ask; j++)
{
line[j] ='#';
}
for (int a = 0; a <= strlen(line); a++)
{
if (line[a] == '#'){
line[a] = '$';
}
printf("%c", line[a]);
}
printf("\n");
}
}
我已经很久没有做过这样的作业了。:)
对于初学者来说,不需要使用数组来输出模式。
您的数组未初始化。所以使用函数
strlen
调用未定义的行为。
并且完全不清楚为什么存在符号
'$'
。
可以在不使用数组和幻数
9
和8
的情况下编写程序。
给你。
#include <stdio.h>
#include <limits.h>
int main( void )
{
const char c = '#';
while ( 1 )
{
printf( "Enter the height (0 - exit): " );
unsigned int n;
if (scanf( "%u", &n ) != 1 || n == 0) break;
if (INT_MAX < n) n = INT_MAX;
putchar( '\n' );
for (unsigned int i = 0; i < n; i++)
{
printf( "%*c", n - i, c );
for (unsigned int j = 0; j < i; j++) putchar( c );
putchar( '\n' );
}
putchar( '\n' );
}
}
程序输出可能看起来像
Enter the height (0 - exit): 10
#
##
###
####
#####
######
#######
########
#########
##########
Enter the height (0 - exit): 9
#
##
###
####
#####
######
#######
########
#########
Enter the height (0 - exit): 8
#
##
###
####
#####
######
#######
########
Enter the height (0 - exit): 7
#
##
###
####
#####
######
#######
Enter the height (0 - exit): 6
#
##
###
####
#####
######
Enter the height (0 - exit): 5
#
##
###
####
#####
Enter the height (0 - exit): 4
#
##
###
####
Enter the height (0 - exit): 3
#
##
###
Enter the height (0 - exit): 2
#
##
Enter the height (0 - exit): 1
#
Enter the height (0 - exit): 0