【发布时间】:2019-02-16 00:05:12
【问题描述】:
所以长度:
int test1 = 1 长度为 1 个字符
int test2 = 37 长度为 2 个字符
int test3 = 82342 的长度为 5 个字符。
我可以使用以下方法找到这些 int 的字符长度:
int character_len = floor(log10(abs(whatever_vairable_here))) + 1;
我想一直数int i = 1; 直到n,但在示例代码中,我只使用了20)。有没有一种方法可以在不使用第一个 while 循环来确定我必须 malloc 的大小的情况下计算出我将使用的字符总数。我想知道我应该有多少空间malloc
int total_characters_needed = 0;
int i = 1;
while (i <= 20) {
total_characters_needed += floor(log10(abs(i))) + 1;`
i++;
}
char *my_numbers_as_a_string = malloc(sizeof(char) * total_characters_needed);
i = 1;
while (i <= 20) {
sprintf(my_numbers_as_a_string, "%d", i);
i++;
}
printf("%s\n", my_numbers_as_a_string);
// Should print out:
// 1234567891011121314151617181920
//
// If the above is unread-able its basically
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
【问题讨论】:
-
你的问题是“从 0 到 n 的所有整数的十进制数字的位数之和是多少?”
-
你不能为总大小设置一个上限吗?这样会分配过多的内存,但要容易得多。
-
为什么你的问题说你以
int i = 0;开头,但你的代码以i = 1开头?哪个是正确的? -
您需要
(10 - 1) * 1 + (21 - 10) * 2 + 1字符来适应所有数字。(10 - 1) * 1用于1到9的范围,(21 - 10) * 2用于10到20的范围,然后1用于终止符。找到模式应该不难 -
你可以使用
asprintf,它不是 ISO-C,而是 GNU-C
标签: c string while-loop char int