gpt4 book ai didi

c - 如何删除c中每行后的最后一个空格?

转载 作者:行者123 更新时间:2023-12-05 02:29:44 24 4
gpt4 key购买 nike

我必须打印出帕斯卡三角形,我的输出如下-

1
1 1
1 2 1

我的代码给出了正确的输出,但在每行之后打印了一个额外的空格。有人可以告诉我如何摆脱它。这是我的代码-

//pascal

#include <stdio.h>

void pascal(int rows)
{
int num = 1, i, j;

for (i = 0; i < rows; i++)
{
for (j = 0; j <= i; j++)
{
if (j == 0 || i == 0)
{
num = 1;
}
else
{
num = num * (i - j + 1) / j;
}
printf("%d ", num);
}
printf("\n");
}
}

int main()
{
int rows;
printf("Please enter how many levels of Pascal's Triangle you would like to see: ");

scanf("%d", &rows);

pascal(rows);

return 0;
}

最佳答案

一种方法是在数字前打印空格,并且仅在 j > 0 时打印:

#include <stdio.h>
void pascal(int rows) {
int num = 1, i, j;

for (i = 0; i < rows; i++) {
for (j = 0; j <= i; j++) {
if (j == 0 || i == 0) {
num = 1;
} else {
num = num * (i - j + 1) / j;
}
if (j > 0) putchar(' '); // conditionally print the space
printf("%d", num); // no space here
}
printf("\n");
}
}

或者在循环之前打印第一个1:

void pascal(int rows) {
int num = 1, i, j;

for (i = 0; i < rows; i++) {
putchar('1'); // print the first 1 here
for (j = 1; j <= i; j++) { // and start the loop at 1
if (i == 0) { // only i needs to be checked here
num = 1;
} else {
num = num * (i - j + 1) / j;
}
printf(" %d", num); // space before the number
}
printf("\n");
}
}

关于c - 如何删除c中每行后的最后一个空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72072422/

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