我无法让 atoll 函数在 c 中正确设置 long long 值。这是我的例子:
#include <stdio.h>
int main(void) {
char s[30] = { "115" };
long long t = atoll(s);
printf("Value is: %lld\n", t);
return 0;
}
这会打印: 值为:0
这虽然有效:
printf("Value is: %lld\n", atoll(s));
这是怎么回事?
最佳答案
首先,让我们回答您的问题:
#include <stdio.h>
#include <stdlib.h> // THIS IS WHAT YOU ARE MISSING
int main(void) {
char s[30] = { "115" };
long long t = atoll(s);
printf("Value is: %lld\n", t);
return 0;
}
然后,让我们讨论并回答“为什么?”:
为了与非常旧的 C 程序(C89 之前)兼容,使用函数而没有先声明它只会从 GCC 生成警告,而不是错误(正如此处第一条评论所指出的,也允许隐式函数声明在 C89 中,因此生成错误是不合适的,这是为什么只生成警告的另一个原因)。 但此类函数的返回类型假定为 int
(不是 stdlib.h
中指定的类型,例如 atoll
),这就是程序意外执行但不会产生错误的原因。如果使用 -Wall
进行编译,您将看到:
Warning: Implicit declaration of function
atoll
当人们使用 atof
而不包含 stdlib.h
时,这个事实通常会让人们感到震惊,在这种情况下,不会返回预期的 double
值。
注意:(作为对问题评论之一的回答)这就是如果没有正确的 header ,atoll
的结果可能会被截断的原因包括。
关于c - 在 C 中将字符串转换为 long long 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15418262/