我正在尝试编写一个简单的 C 代码来显示 C 中各种变量类型的最大值和大小。但是,我得到了一些奇怪的输出,例如 sizeof() 运算符为某些变量返回 -1类型。我认为问题在于我在 printf 命令中使用的说明符,因为当我将下面代码中的“%e”更改为“%d”时,即使对于那些我没有更改的说明符,我也会得到非常不同的输出。我的问题是如何获得我正在寻找的正确输出,即第一列中变量类型的最大值和第二列中变量类型的大小。
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
int main()
{
printf("Float max: %e Nbytes: %d\n",FLT_MAX,sizeof(float));
printf("Double max: %e Nbytes: %d\n",DBL_MAX,sizeof(double));
printf("Int max: %e Nbytes: %d\n",INT_MAX,sizeof(int));
printf("UnInt max: %e Nbytes: %d\n",UINT_MAX,sizeof(unsigned int));
printf("LongIntmax: %e Nbytes: %d\n",LONG_MAX,sizeof(long));
printf("UnLong max: %e Nbytes: %d\n",ULONG_MAX,sizeof(unsigned long));
printf("Longlongmax: %e Nbytes: %d\n",LLONG_MAX,sizeof(long long));
exit(0);
}
我从编写的代码中得到的输出如下:
Float max: 3.402823e+38 Nbytes: 4
Double max: 1.797693e+308 Nbytes: 8
Int max: 1.797693e+308 Nbytes: 2147483647
UnInt max: 1.797693e+308 Nbytes: -1
LongIntmax: 1.797693e+308 Nbytes: -1
UnLong max: 1.797693e+308 Nbytes: -1
Longlongmax: 1.797693e+308 Nbytes: -1
但是,如果我将所有“%e”切换为“%d”并再次运行代码,我会得到:
Float max: 4 Nbytes: -1290994504
Double max: 8 Nbytes: 605613584
Int max: 2147483647 Nbytes: 4
UnInt max: -1 Nbytes: 4
LongIntmax: -1 Nbytes: 8
UnLong max: -1 Nbytes: 8
Longlongmax: -1 Nbytes: 8
第一次运行的第二列输出成为第二次运行的第一列输出。我不确定这里发生了什么。再次,我认为我将错误的说明符与 *_MAX 常量联系起来,但我不确定是否还遗漏了另一个问题。
最佳答案
是的,问题在于说明符 - 您需要让它们匹配参数 %f
/%e
/%g
对于 double
(和 float
被提升), %d
已签名,%u
对于未签名的。和l
在每个 long
的中间。最后size_t
需求%zu
.
printf("Float max: %f Nbytes: %zu\n",FLT_MAX,sizeof(float));
printf("Double max: %f Nbytes: %zu\n",DBL_MAX,sizeof(double));
printf("Int max: %d Nbytes: %zu\n",INT_MAX,sizeof(int));
printf("UnInt max: %u Nbytes: %zu\n",UINT_MAX,sizeof(unsigned int));
printf("LongIntmax: %ld Nbytes: %zu\n",LONG_MAX,sizeof(long));
printf("UnLong max: %lu Nbytes: %zu\n",ULONG_MAX,sizeof(unsigned long));
printf("Longlongmax: %lld Nbytes: %zu\n",LLONG_MAX,sizeof(long long));
你得到-1
因为当格式字符串与参数不匹配时,您会触发未定义的行为。
关于c - C 中的 limit.h *_MAX 常量的正确说明符是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16949103/