我写了以下代码:
#include <stdio.h>
double recalc(double a);
int main(void)
{
double a;
printf("\nPlease enter a duration in ms. This program will "
"calculate the corresponding amount of hours.\n");
scanf("%lf", &a);
printf("Your input in ms is %.15f hours\n", recalc(a));
return 0;
}
double recalc(double a)
{
a = a/1000/60/60;
return a;
}
因此,该程序将ms转换为小时。 到目前为止,非常好。
我在这里使用%。15f保持合理的尺寸,但如果我输入...让我们说0.0000000000001,我的15位小数是不够的。另外,但这只是化妆品,如果我输入360000000,我想在最后切断无效的0。 有人为此得到了解决方案吗?
答案 0 :(得分:1)
尝试捕获指数并sprintf值。根据需要删除尾随零。
#include <stdio.h>
#include <string.h>
char *recalc(double a);
int main(void)
{
double a;
printf("\nPlease enter a duration in ms. This program will calculate the corresponding amount of hours.\n");
scanf("%lf", &a);
printf("Your input in ms is %s hours\n", recalc(a));
return 0;
}
char *recalc(double a)
{
static char value[100] = "";
char *sign = NULL;
size_t len = 0;
int exp = 10;
a = a/1000.0/60.0/60.0;
sprintf ( value, "%e", a);
sign = strpbrk ( value, "-");
if ( sign) {
sscanf ( sign + 1, "%d", &exp);
exp += 5;
}
sprintf ( value, "%.*f", exp, a);
len = strlen ( value) - 1;
while ( value[len] == '0') {
value[len] = '\0';
len--;
}
if ( value[len] == '.') {
value[len] = '\0';
}
return value;
}