有关宽度如何作为参数传递给printf 的示例,请参阅printf format string 中的“宽度字段”小节。
我从Finding the length of an integer in C得到宽度算法。
我在Code Chef 测试了我的代码。如果您打算使用gcc 编译此代码,则需要-lm 选项为math.h 引入库。见How to compile a C program that uses math.h?。
如果您需要不同的表头,您可以调整printspaces(11-w) 中的常量 11 和printspaces(5-w) 中的 5,直到数据与表头对齐。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int width(int v){
return floor(log10(abs(v))) + 1;
}
int printspaces(int s){
int x;
for (x=0;x<s;x++)
printf(" ");
}
int main(void){
int i,j,w;
int a[3][4] = {{1,200,3,300},{2,3,1,50},{3,1000,4,1200}};
//int a[3][4] = {{10,200,37,3000},{278,3565,1131,50},{390,100,4567,1200}};
char *separator[4] = {"","","","\n"};
printf("Process No.(Size) Block No.(Size)\n");
for(i=0;i<3;i++){
for (j=0;j<4;j++){
w = width(a[i][j]);
if (j%2==0){
printspaces(11-w);
printf("%*d%s",w,a[i][j],separator[j]);
}
else{
printf("(%*d)",w,a[i][j]);
printspaces(5-w);
printf("%s",separator[j]);
}
}
}
return 0;
}
以下是结果(代码中的两个示例数组):
int a[3][4] = {{1,200,3,300},{2,3,1,50},{3,1000,4,1200}};
Process No.(Size) Block No.(Size)
1(200) 3(300)
2(3) 1(50)
3(1000) 4(1200)
int a[3][4] = {{10,200,37,3000},{278,3565,1131,50},{390,100,4567,1200}};
Process No.(Size) Block No.(Size)
10(200) 37(3000)
278(3565) 1131(50)
390(100) 4567(1200)