dasblinkenlight 和 Eric 的跳板——你可以做的一个例子是简单地编辑你的代码,如下所示:
#include <stdio.h>
#include <stdlib.h>
int main()
{
double n = 72382.413651;
//int len;
//len = sizeof(n);
//printf("%d\n", len);
printf("%5.6f\n", n);
getchar();
}
这将打印出与声明中完全相同的值。
或者,假设您必须处理在不同位置带有小数点的数字,但希望格式在整齐的列中。你可以这样做:
#include <ansi_c.h>
#include <stdio.h>
#include <stdlib.h>
//varible format codes for varying decimal point positions
char *format[]={"%0.9f\n",
"%0.8f\n",
"%0.7f\n",
"%0.6f\n",
"%0.5f\n",
"%0.4f\n",
"%0.3f\n",
"%0.2f\n",
"%0.1f\n",
"%0.0f.\n"};
int main()
{
char val[25];
char dp[]={"."};//will search for position of decimal point in string
//for the purposes of illustration, create some floating point values
double a = .723824136;
double s = 7.23824136;
double d = 72.3824136;
double f = 723.824136;
double g = 7238.24136;
double h = 72382.4136;
double j = 723824.136;
double k = 7238241.36;
double l = 72382413.6;
double m = 723824136.;
//put in string of standard length,
//format output according to decimal position
sprintf(val, "%0.12f", a); printf( format[strcspn(val, dp)], a);
sprintf(val, "%0.12f", s); printf( format[strcspn(val, dp)], s);
sprintf(val, "%0.12f", d); printf( format[strcspn(val, dp)], d);
sprintf(val, "%0.12f", f); printf( format[strcspn(val, dp)], f);
sprintf(val, "%0.12f", g); printf( format[strcspn(val, dp)], g);
sprintf(val, "%0.12f", h); printf( format[strcspn(val, dp)], h);
sprintf(val, "%0.12f", j); printf( format[strcspn(val, dp)], j);
sprintf(val, "%0.12f", k); printf( format[strcspn(val, dp)], k);
sprintf(val, "%0.12f", l); printf( format[strcspn(val, dp)], l);
sprintf(val, "%0.12f", m); printf( format[strcspn(val, dp)], m);
getchar();
}