我正在尝试编写一个简单的 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 常量,但我不确定是否还有我遗漏的另一个问题。