我必须打印出帕斯卡三角形,我的输出如下-
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");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)