C 语言基础二:数据类型

139 阅读2分钟

C 语言基础二:数据类型

一. 字节与位数关系

单位描述换算关系
位(bit)计算机最小存储单位,只有0/1
字节(Byte)8位组成一字节1Byte = 8bit
千字节(Byte)1024字节1KB = 1024Byte
兆字节(Byte)1024千字节1MB = 1024KB

二. 整数类型

数据类型字节数位数取值范围
char18有符号-128到127,无符号0-255
short216有符号-32768到32767,无符号0-65535
int432有符号 - 2,147,483,648 到 2,147,483,647
long4(32位系统)/8(64位系统)32/64很大
long long864更大
  • 无符号整数 位数:n 取值范围:0 到 2ⁿ - 1 示例:unsigned char(8 位)的取值范围是 0 到 2⁸ - 1 = 255
  • 有符号整数(补码表示 位数:n(最高位为符号位) 取值范围:-2ⁿ⁻¹ 到 2ⁿ⁻¹ - 1 示例:signed char(8 位)的取值范围是 -2⁷ = -128 到 2⁷ - 1 = 127

三. 浮点类型

数据类型字节数位数精度范围
float4326-7位有效数字
double86415-16位有效数字
long double8/10/1664/80/128精度很高

四. 布尔类型(C99及以后版本)

#include <stdio.h>

//需要引入
#include <stdbool.h>

int main(void){
    bool isReady = true;
    bool isDid = false;
    
    printf("isReady:%d\n",isReady);  // isReady:1
    printf("isReady:%s\n",isReady ? "true": "false"); //isReady:true

    return 0;
}

五. 空类型

  • void

六. 派生类型

  1. 数组
  2. 指针
  3. 结构体
  4. 联合体
  5. 枚举
enum WeakDay{
  MON,
  TRU,
  WED
};

int main(void){
  
  enum  WeakDay today = TRU;
  if(today == WED){
      printf("yes");
  }
  return 0;
}

  1. 字符串
    char c1 = 'c';
    printf("c1:%c\n",c1);
    char c2[] = "helloworld"; //字符串中间有空格不行
    printf("c2:%s\n",c2);

七. 各种类型色输出

#include <stdio.h>

//需要引入
#include <stdbool.h>

int main(void){
    //bool类型
    bool isReady = true;
    printf("isReady:%d\n",isReady);  // isReady:1
    printf("isReady:%s\n",isReady ? "true": "false"); //isReady:true
    
    //sizeof
    printf("int: %zu 字节\n",sizeof(int)); // int: 4 字节
    
    //整形的输出
    short a1 = 1;
    int a2 = 2;
    long a3 = 3;
    printf("a1:%hd\n",a1);
    printf("a2:%d\n",a2);
    printf("a3:%ld\n",a3);
    
    //浮点型输出
    float b1= 1.234567;
    double b2= 1.234567;
    printf("b1:%f\n",b1);
    printf("b2:%.2lf\n",b2);
    
    //字符串
    char c1 = 'c';
    printf("c1:%c\n",c1);
    char c2[] = "helloworld"; //字符串中间有空格不行
    printf("c2:%s\n",c2);
    
    

    return 0;
}

八. 强制类型转换

    int a = 15;
    double b = (double)a;
    printf("a:%d\n",a);
    printf("b:%lf\n",b);