C語言基本資料型態與輸入輸出

Tiny_Murky
5 min readFeb 5, 2023

--

攝影師:Pixabay: https://www.pexels.com/zh-tw/photo/php-270348/

前言:

這是我第一次寫Blog,想要紀錄我的學習歷程,這裡主要是我的學習筆記為主。

目前我學習C語言教學手冊,此篇為第三章與第四章的內容。系統我是使用Debian 11 + gcc,所以有些地方和windows不一樣。

以下內容摘自洪維恩編寫之「C語言教學手冊」加上我的一點整理。

基本資料型態

C語言中常見的資料型態有下表中幾種。

C語言常見資料型態

int

int 表示整數,由4個位元組組成,位元組第1碼代表正負號,範圍由-2,147,483,648 to 2,147,483,647 (-2³¹~2³¹-1)。

如果前方加上unsigned變成 unsigned int 範圍變成0至4,294,967,295,因為第1碼不需要代表正負號,範圍是0 to 2³²-1

short

short 是只有2bytes 的整數,範圍是-32,768 ~32,767 (-2¹⁵~2¹⁵-1), unsigned short 則是 0 to 65,535(0~2¹⁶-1)

long

long是長整數,64位元上是8bytes,32位元是4bytes,64位元上的範圍是2-⁶³ to2 ⁶³-1, unsigned long 範圍是 0 to 2 ⁶⁴-1

如果在數字後面加一個L,可以代表是long int,long int 也是4bytes,和int一樣,如: long num = 123L;

int64_t

int64_t需要在表頭先import <stdint.h>才可以使用,它為8bytes,範圍是-2⁶³ to 2⁶³-1

unint64_t

int64_t unsigned版本,範圍是 0 to 2⁶⁴-1

char

char 對應0~127個ASCII table符號,但是他本身儲存的方式是用數字儲存,如果是單寫一個char記得使用單引號如:’a’,雙引號是給string使用的

#include <stdio.h>

int main (void) {
char ch = 'a';
printf("ch of a = %c\n", ch);
printf("ASCII of a is: %d\n", ch);//a 就是數字97

ch = 98;
printf("ch of 98 = %c\n", ch); //數字98代表b
printf("ASCII of 98 is: %d\n", ch);

ch = 2;
printf("ch of 2 = %c\n", ch);
printf("ASCII of 2 is: %d\n", ch);

ch = '2';
printf("ch of \'2\' = %c\n", ch);
printf("ASCII of \'2\' is: %d\n", ch);//文字的2 其實是50
return 0;
}
# return
ch of a = a
ASCII of a is: 97
ch of 98 = b
ASCII of 98 is: 98
ch of 2 =
ASCII of 2 is: 2
ch of '2' = 2
ASCII of '2' is: 50

float

float是4bytes浮點數,可以用來紀錄有小數點的數字,範圍是2.939x10^-38 to 3.403x10+38,約可儲存7~8個數字,如果在數字後面加一個F,可以代表是float,如: float num = 123.456F;

double

double是8bytes浮點數,可以用來紀錄有小數點的數字,範圍是5.563x 10-309至1.798x10+308 ,約可儲存15~16個數字

溢位

如果資料的大小超過可以儲存的上限就會發生溢位,電腦只會讀取最後幾個位元,像是char讀取8位元,如果char儲存數字298,會變成42,算法為298 mod 256 = 42

跳脫符號

常見跳號

跳脫字元為char,透過反斜線\加上特定字母組成,可以實現特定的文字功能,如果是單獨表示請用單引號表達,如: ch = '\n';

sizeof

要查詢變數or特定資料佔有的空間,可以使用sizeof()

#include <stdio.h>
#include <stdint.h>

int main (void) {
char ch;
float num;

/*sizeof 會回傳unsigned long int
*所以我把他轉換成int
*但是不轉換也可以跑
* */
printf("sizeof(2L)=%d\n", (int) sizeof(2)); //2L 代表長整數2
printf("sizeof(ch)=%d\n", (int) sizeof(ch)); //空的char的大小
printf("sizeof(num)=%d\n", (int) sizeof(num)); //空的float的大小


printf("sizeof(int)=%d\n", (int) sizeof(int)); //int的大小
printf("sizeof(long)=%d\n", (int) sizeof(long)); //long的大小
printf("sizeof(double)=%d\n", (int) sizeof(double)); //long的大小
printf("sizeof(int64_t)=%d\n", (int) sizeof(int64_t)); //int64_t的大小
}
# output
sizeof(2L)=4
sizeof(ch)=1
sizeof(num)=4
sizeof(int)=4
sizeof(long)=8
sizeof(double)=8
sizeof(int64_t)=8

標準輸入輸出<stdio.h>

以下介紹<stdio.h>當中會使用的函數,printf、scanf、getchar與文字標準格式

printf()

--

--