问题提出:
如果有一个问题,输入n,要求输出一个小数,保留小数点后n位。(用C写),此时可以用printf() * 的修饰符来解决这个问题。
以下代码表明这个工作原理:(来自C primer PULS)
#include<stdio.h>
int main()
{
unsigned width,precision;
int number = 256;
double weight = 242.5;
printf("What filed width?\n");
scanf("%d",&width);
printf("The number is:%*d:\n",width,number);
printf("Now enter a width and a precision:\n");
scanf("%d %d",&width,&precision);
printf("Weight=%*.*f\n",width,precision,weight);
return 0;
}
#include<stdio.h>
int main()
{
unsigned width,precision;
int number = 256;
double weight = 242.5;
printf("What filed width?\n");
scanf("%d",&width);
printf("The number is:%*d:\n",width,number);
printf("Now enter a width and a precision:\n");
scanf("%d %d",&width,&precision);
printf("Weight=%*.*f\n",width,precision,weight);
return 0;
}
变量width提供字符宽度,而number就是要打印的数字。因为在说明符中*在d前面,所以在printf()的参数列表中
width在number前面。同样,width和precision共同提供来打印weight的格式化信息。下面是运行的结果:
What filed width?6
The number is: 256:
Now enter a width and a precision:
8 3
Weight= 242.500
--------------------------------