C中的每个变量都有一个关联的数据类型。每种数据类型需要不同数量的内存,并具有一些可以在其上执行的特定操作。让我们对它们进行一个简短的描述:
以下是C中使用的一些非常常见的数据类型的示例:
- char: C语言中最基本的数据类型。它存储一个字符,并且几乎在所有编译器中都需要一个字节的内存。
- int:顾名思义,int变量用于存储整数。
- float:用于存储单精度十进制数(带浮点值的数字)。
- double:用于存储双精度精度的十进制数字(带浮点值的数字)。
不同的数据类型还可以存储数字的范围也不同。这些范围可能因编译器而异。以下是32位gcc编译器上的范围以及内存要求和格式说明符的列表。
Data Type |
Memory (bytes) |
Range |
Format Specifier |
---|---|---|---|
short int |
2 |
-32,768 to 32,767 |
%hd |
unsigned short int |
2 |
0 to 65,535 |
%hu |
unsigned int |
4 |
0 to 4,294,967,295 |
%u |
int |
4 |
-2,147,483,648 to 2,147,483,647 |
%d |
long int |
4 |
-2,147,483,648 to 2,147,483,647 |
%ld |
unsigned long int |
4 |
0 to 4,294,967,295 |
%lu |
long long int |
8 |
-(2^63) to (2^63)-1 |
%lld |
unsigned long long int |
8 |
0 to 18,446,744,073,709,551,615 |
%llu |
signed char |
1 |
-128 to 127 |
%c |
unsigned char |
1 |
0 to 255 |
%c |
float |
4 |
%f |
|
double |
8 |
%lf |
|
long double |
16 |
%Lf |
我们可以使用sizeof()运算符来检查变量的大小。有关各种数据类型的用法,请参见以下C程序:
C
#include
int main()
{
int a = 1;
char b = 'G';
double c = 3.14;
printf("Hello World!\n");
// printing the variables defined
// above along with their sizes
printf("Hello! I am a character. My value is %c and "
"my size is %lu byte.\n",
b, sizeof(char));
// can use sizeof(b) above as well
printf("Hello! I am an integer. My value is %d and "
"my size is %lu bytes.\n",
a, sizeof(int));
// can use sizeof(a) above as well
printf("Hello! I am a double floating point variable."
" My value is %lf and my size is %lu bytes.\n",
c, sizeof(double));
// can use sizeof(c) above as well
printf("Bye! See you soon. :)\n");
return 0;
}
输出:
Hello World!
Hello! I am a character. My value is G and my size is 1 byte.
Hello! I am an integer. My value is 1 and my size is 4 bytes.
Hello! I am a double floating point variable. My value is 3.140000 and my size i
s 8 bytes.
Bye! See you soon. :)
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。