1

嗨,我有 2 个问题,第一个问题是标题中的问题,另一个问题在这里: unsigned long long 是否是最大的整数(可以容纳最大数量的字符)?因为我需要一个可以容纳几百万个字符(数字)的 int 这可能吗?我正在用 C 编写代码,这将我与另一个问题联系起来,如何在屏幕上显示数字数量?需要这样吗?:

printf("%d", intName.length)

感谢大家!!

4

4 回答 4

1

我假设当您提到字符数时,您的意思是数字中的位数。如果是这样,那么这个问题包含您需要知道的所有内容,并包含与此类似的代码

int numberOfDigits(unsigned long long n) 
{
    if (n == 0)
        return 0;
    return floor( log10( abs( n ) ) ) + 1;
}

至于保存几百万位数字,您可能希望使用包含该函数的库,例如The GNU Multiple Precision Arithmetic Library

size_t mpz_sizeinbase( const mpz_t op, int base )

它会告诉你你的号码有多少位数。

于 2013-12-30T23:23:07.290 回答
0
printf("%llu", xxxxxxxxx);

 the ll (el-el) long-long modifier with the u (unsigned) conversion

你也可以使用

 uint64_t a;
 uint32_t b;

但是您需要包含 inttypes.h 库,该库为您提供 int32_t、int64_t、uint64_t 等类型。

于 2013-12-30T23:13:14.350 回答
0

C99 提供了 intmax_t(和 uintmax_t),它将是支持的最大整数类型(通常为 64 位)。

假设你有一个符合 C99 snprintf 那么你可以得到位数:

length = snprintf(NULL, 0, "%llu", value);

对于 unsigned long long 值(和 %ju 对于 uintmax_t。)

否则,您必须在 (yuk) 中传递一个缓冲区或手动执行以下操作:

length = value < 10 ? 1 :
         value < 100 ? 2 :
         ...

还有yuk!

但是,如果您真的想要百万位数的整数,这一切都无关紧要,在这种情况下,您将需要使用诸如 gmp 之类的库来处理如此大的数字。

于 2013-12-30T23:36:46.547 回答
0

给定位长类型的无符号整数的最大十进制长度由下式bitlen给出1 + floor(log10(2^bitlen-1))(数学上,不考虑溢出和舍入误差)。近似值1/log2(10) ~ 4004.0/13301(通过连分数获得,参见http://en.wikipedia.org/wiki/Continued_fraction)导致公式1 + bitlen * 4004 / 13301(计算上,即除法向下舍入)。数学细节在下面代码片段的评论中给出。

#include <limits.h>
#include <stdio.h>

/**
 * Maximal number of digits in the decimal representation of an unsigned type.
 *
 * floor( log2(2^bitlen - 1) / log2(10) ) == floor( bitlen / log2(10) )
 * otherwise an integer n would exist with
 *     log2(2^bitlen - 1) / log2(10) < n < bitlen / log2(10)
 *     log2(2^bitlen - 1) < n * log2(10) < bitlen
 *     2^bitlen - 1 < 2^(n * log2(10)) < 2^bitlen
 *     2^bitlen - 1 < (2^log2(10))^n < 2^bitlen
 *     2^bitlen - 1 < 10^n < 2^bitlen
 *     which is impossible
 *
 * 1 / log2(10) ~ 0.301029995663981
 * 4004 / 13301 ~ 0.30102999774453
 *
 *     1 + floor( log10(2^bitlen - 1) )
 *  == 1 + floor( log2(2^bitlen - 1) / log2(10) )
 *  == 1 + floor( bitlen / log2(10) )
 *  <= 1 + floor( bitlen * 4004.0 / 13301 )
 *  == 1 + bitlen * 4004 / 13301
 * with equality for bitlen <= 13300 == 8 * 1662.5
 */
#define DECLEN(unsigned_t) (1 + CHAR_BIT*sizeof(unsigned_t) * 4004 / 13301)

int main(int argc, char *argv[]) {
    printf("unsigned char      : %zu\n", DECLEN(unsigned char));
    printf("short unsigned     : %zu\n", DECLEN(short unsigned));
    printf("unsigned           : %zu\n", DECLEN(unsigned));
    printf("long unsigned      : %zu\n", DECLEN(long unsigned));
    printf("long long unsigned : %zu\n", DECLEN(long long unsigned));
    return 0;
}
于 2015-05-05T14:48:37.590 回答