C語言中有哪些不同的資料型別?


資料型別是記憶體位置或變數的宣告。資料可以是不同型別的,以下是一些C語言中資料型別的示例:

整數、有理數、自然數、實數、複數、向量、字元等。

對於機器硬體來說,資料都是以有限長度的0和1的二進位制數字串進行編碼的。在機器中,整數資料在算術邏輯單元(ALU)中處理,分數資料在浮點單元(FPU)中處理。這反映在高階語言的內建或基本資料型別中。

內建資料型別

在C語言中,有不同的內建資料型別,其中一些如下所示:

int、float、char、unsigned int、unsigned char、long int、double等。

資料的使用

在C語言中,可以使用不同的型別以不同的方式儲存資料。以下是一些示例:

  • char 字串,grade='A';
  • int 計數,index=10;
  • float 平均值=6.9;

在上面的示例中,char、int、float 是內建資料型別,而string、grade 是 char 型別的變數。

  • Grade='A' 將變數 grade 初始化為 'A' 的字元程式碼。

  • Count 和 index 是 int 型別的變數。

  • 並且 index=10 將變數初始化為 10 的二進位制表示。

示例

下面是C程式,用於**找出變數和內建資料型別的大小**:

 線上演示

#include<stdio.h>
int main(){
   int x = 10;
   char c;
   printf("Size of variable x = %ld bytes
",sizeof(x));    printf("Size of variable c = %ld byte
",sizeof(c));    printf("Size of short is %ld bytes
",sizeof(short));    printf("Size of int is %ld bytes
",sizeof(int));    printf("Size of long is %ld bytes
",sizeof(long));    printf("Size of float is %ld bytes
",sizeof(float));    printf("Size of double is %ld bytes
",sizeof(double));    printf("Size of long double is %ld bytes
",sizeof(long double));    printf("Size of char is %ld bytes
",sizeof(char));    printf("Size of void is %ld bytes
",sizeof(void));    return 0; }

輸出

執行上述程式時,會產生以下結果:

Size of variable x = 4 bytes
Size of variable c = 1 byte
Size of short is 2 bytes
Size of int is 4 bytes
Size of long is 4 bytes
Size of float is 4 bytes
Size of double is 8 bytes
Size of long double is 16 bytes
Size of char is 1 bytes
Size of void is 1 bytes

更新於: 2021年9月3日

957 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告