【发布时间】:2014-11-22 23:52:36
【问题描述】:
我正在编写一个简单的课堂程序。我已经完成了,别担心,我不是要求任何人做我的功课。让我用一个例子来解释我想要什么。
我的程序要求一定数量的位并将其转换为 mb、kb 和字节。所以,如果我输入 1 位,输出是:
1 in megabytes is: 0.000000119209290
1 in kilobytes is: 0.000122070312500
1 in bytes is: 0.125000000000000
1 in bits is: 1
所以,我的问题只是一个审美问题:我怎么能不显示不必要的小数位?例如,在字节中,我只想打印 0.125,而不是 15 位小数,这一点都不漂亮。
源码为:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
unsigned long long int bits;
printf("Input a quantity of bits: \n");
scanf("%lld", &bits);
/*
* 1 byte = 8 bits.
* 1 kilobyte = 1024 bytes.
* 1 megabyte = 1024 kilobytes.
*/
long double by = ((double) bits) / ((double) 8);
long double kb = ((double) by) / ((double) 1024);
long double mb = ((double) kb) / ((double) 1024);
printf("%lld in megabytes is: %.15Lf\n", bits, mb);
printf("%lld in kilobytes is: %.15Lf\n", bits, kb);
printf("%lld in bytes is: %.15Lf\n", bits, by);
printf("%lld in bits is: %lld\n", bits, bits);
return(0);
}
PS:我知道我在 printf 中指定了 15 位小数,我只是在尝试哪种方式是我输出值的最佳方式。
提前谢谢你!
【问题讨论】:
-
stackoverflow.com/questions/277772/… 这可能对你有帮助。
-
问题是使用 %g 我得到兆字节作为指数,我想要一个小数。
-
你读过printf(3)