c - 如何在C中删除最顶部的空格
问题描述
#include <cs50.h>
#include <stdio.h>
//Prototypes.
void print_hashes(int n);
void print_spaces(int n);
//Main function.
int main(void)
{
//Recieves,checks and saves user input. Prompts to enter information again if invalid.
int height = -1;
while (height < 1 || height > 8)
{
height = get_int("Height: ");
}
//Outputs graphic to the screen with the use of logic with functions.
for (int h = 0; h <= height; h++)
{
print_spaces(height - h);
print_hashes(h);
printf(" ");
print_hashes(h);
printf("\n");
}
}
//Function for printing hashes to the screen.
void print_hashes(int n)
{
for (int c = 0; c < n; c++)
{
printf("#");
}
}
//Function for printing spaces to the screen so the hashes will be in the right spot.
void print_spaces(int n)
{
for (int c = 0; c < n; c++)
{
printf(" ");
}
}
输出:
Height: 8
# #
## ##
### ###
#### ####
##### #####
###### ######
####### #######
######## ########
你看到在顶部,在高度的正下方,金字塔图形和高度之间有一个空间:8 我不想要那个。另外,我是一个大型 C 初学者,没有复杂的库和主题,请只使用普通的基本语法。
到目前为止我已经尝试过
if (h > 0)
{
printf("\n");
}
在这样的主for循环中
#include <cs50.h>
#include <stdio.h>
//Prototypes.
void print_hashes(int n);
void print_spaces(int n);
//Main function.
int main(void)
{
//Recieves,checks and saves user input. Prompts to enter information again if invalid.
int height = -1;
while (height < 1 || height > 8)
{
height = get_int("Height: ");
}
//Outputs graphic to the screen with the use of logic with functions.
for (int h = 0; h <= height; h++)
{
print_spaces(height - h);
print_hashes(h);
printf(" ");
print_hashes(h);
if (h > 0)
{
printf("\n");
}
}
}
//Function for printing hashes to the screen.
void print_hashes(int n)
{
for (int c = 0; c < n; c++)
{
printf("#");
}
}
//Function for printing spaces to the screen so the hashes will be in the right spot.
void print_spaces(int n)
{
for (int c = 0; c < n; c++)
{
printf(" ");
}
}
但得到这样的输出:
Height: 8
# #
## ##
### ###
#### ####
##### #####
###### ######
####### #######
######## ########
我想知道我做错了什么以及如何解决它,以便顶部没有空间。记住我刚开始没有高级库或主题这是我的第一个问题集。
解决方案
如果您不希望包含 0 个哈希的行,请不要将其包含在循环中:
for (int h = 1; h <= height; h++)
从 1 开始循环会从循环中删除空行。
推荐阅读
- python - 使用 .env 时出现 NameError: name 'config' is not defined
- regex - 正则表达式匹配从第 n 次出现的字符开始的所有内容
- python - 为什么加载大量数据时 Odoo 性能太慢?
- r - R:在列表列上使用 rollapply
- c - 如何存储指向在 Fsm 中接受参数的函数的指针?
- python - Python - 将 XLSX 转换为 PDF
- c# - 使用异步时的文件写入问题
- java - 如何去除soapAction
- swift - 快速,标签中的文本在 viewDidAppear() 中没有改变
- c# - 如何在 Xamarin Forms 中设置 UI?