如何在c中右对齐输出数字(或文本)?

时间:2017-01-07 12:32:36

标签: c alignment printf

我有一个任务是从用户那里得到一个正整数,然后打印一个看起来像这样的三角形(例如,对于整数5):

          1
        1 2
      1 3 5
   1 4 7 10
1 5 9 13 17

这是我设法制作的代码:

int num, line,addition,sum,termNum;
printf("Enter a positive integer: ");
scanf("%d",&num);

printf("%d\n",1);

for (line=2;line<=num;line++)
{
   addition = line-1;
   termNum=1;
   printf("%d ",termNum);

   for (sum=2;sum<=line;sum++)
   {
       termNum+=addition;
       printf("%d ",termNum);
   }
   printf("\n");

}

但是输出没有与右边对齐,它看起来像这样:

1
1 2
1 3 5
1 4 7 10
1 5 9 13 17

我无法创建函数或使用数组,只能使用循环和ifs,以及各种控制字符,例如%c%s%d%-12c等... 变量类型必须是int,double,char。 (不是字符串或字符*等)

有什么想法吗? 感谢。

2 个答案:

答案 0 :(得分:0)

OP需要轻推预先计算最大线宽。

下面填空的代码计算最大线宽,这似乎是OP的绊脚石。

int main(void) {
  int x = 5;
  int width = 0;
  for (int col = 0; col < ___ ; col++) { // How many iterations?
    int value = col* ___ + ___;          // Determine each value: 1 5 9 13 17      
    // find print width
    do {
      width++;  // add 1 per digit       
      value /= ___;                      // What base is the number displayed?
    } while (value > ___);               // When to quit (hint:  not much)
    width++;  // add 1 for ' ' separator 
  }
  printf("%d\n", width);                 // Should be a dozen
}

替代

  for (int col = 0; col < ___ ; col++) {
    int value = col* ___ + ___;
    width += snprintf(NULL, 0, "%d ", value);
  }

答案 1 :(得分:-1)

最大打印数量将是最后一个数字。就行了 num和列num。因此它将是1 + (num - 1) ^ 2

十进制数N的打印宽度为ceil(log(N+1) / log(10))

对齐数字的最简单方法是将它们打印出来 width,即最大数量的宽度: ceil(log(1 + (num - 1) ^ 2) / log(10))

int num, line, addition, sum, termNum;
printf("Enter a positive integer: ");
scanf("%d", &num);
int width = ceil(log10(1 + 1 + (num - 1) * (num - 1)));
char format[] = "%0000000000d%c";
sprintf(format, "%%%dd%%c", width);
for (sum = 1 + 1; sum <= num; sum++) {
    int i;
    for (i = 0; i <= width; i++)
        putchar(' ');
}
printf(format, 1, '\n');
for (line = 2; line <= num; line++) {
    for (sum = line + 1; sum <= num; sum++) {
        int i;
        for (i = 0; i <= width; i++)
            putchar(' ');
    }
    addition = line - 1;
    termNum = 1;
    printf(format, termNum, ' ');
    for (sum = 2;sum <= line; sum++) {
        termNum += addition;
        printf(format, termNum, ' ');
    }
    printf("\n");
}