我有这段代码:
#include <stdio.h>
#include <conio.h>
void main()
{
int n = 5;
clrscr();
printf("n=%*d", n);
getch();
}
我得到的输出是:
n= 5
。为什么有一个空格?它是如何生成的?代码中的*
有什么用途?当你不确定的时候,请阅读文档:
*
:宽度没有在格式字符串中指定,而是作为一个额外的整数值参数在要格式化的参数之前指定。
然而,您似乎使用方法错误。正确的使用方法应该是这样的:
printf("n=%*d", 2, n);
在C手册中明确提到了这一点。
Richard J. Ross III已经给出了答案。只是再次引用手册中的内容。
宽度没有在格式字符串中指定,而是作为一个额外的整数值参数在要格式化的参数之前指定。
考虑以下代码:
#include<stdio.h>
main()
{
int a,b;
float c,d;
a = 15;
b = a / 2;
printf("%d\n",b);
printf("%3d\n",b);
printf("%03d\n",b);
c = 15.3;
d = c / 3;
printf("%3.2f\n",d);
}
输出结果将是:
7
7
007
5.10
printf
函数来格式化输出。希望能帮到你。 :)使用这个*
,您可以使用变量设置打印的宽度。