【发布时间】:2017-10-16 06:45:43
【问题描述】:
我从 Linux 命令行在 Nano 中编写了以下代码,以在编译时出错:
我想知道我需要对代码进行哪些更改才能使其正确编译。我正在尝试获取列出的每种数据类型中的位数以打印在一行上。
#include<stdio.h>
int main(void){
char A;
unsigned char B;
int a;
unsigned int b;
long c;
unsigned long d;
float e;
double f;
long double g;
printf(
"%c %c %i %u %li %lu %f %lf %Lf\n",
sizeof(char), sizeof(unsigned char),
sizeof(int), sizeof(unsigned int),
sizeof(long), sizeof(unsigned long),
sizeof(float), sizeof(double), sizeof(long double)
);
return 0;
}
【问题讨论】:
-
在
printf中使用%zu而不是%whatever。它的参数不是它们各自的类型,而是size_t,因为sizeof返回的是size_t类型。 -
@zbw 这将是一个很好的答案,带有一些链接和相关代码的固定版本。
-
寻找类似的问题,我发现this one 有一个很好的解释。我无法给出更好的答案,所以我只提供链接。
-
另外,
sizeof返回字节数,这通常比位数更有用。乘以 8 得到位数 -
@zbw:
8几乎肯定会起作用,但CHAR_BIT更清晰。 (假设您在程序中有一些其他值恰好是8,并且您想将其更改为16。如果您没有太多不相关的@987654336 出现,那么进行更改会容易得多@. 最好避免使用幻数。
标签: c linux command sizeof nano