fqy131314

C++——数据类型之间的转换

类型转换的概念

为什么需要“类型转换”

参与运算的两个操作数的数据类型,必须相同!

类型转换的类别:

1.隐式类型转换 (自动完成转换)

  1. 算数转换
  2. 赋值转换
  3. 输出转换

2.强制类型转化

隐式类型转换

算数转化

(+,-,*,/,%)

char ,   int,   long,   long long,  float,  double

15 + 3.14  =>   15.0  +  3.14

赋值转换

#include <stdio.h>

int main(void) {

       int x;

    // 计算结果31.4 转换为int类型,因为赋值符号的左边变量的类型是int类型

       x = 3.14 * 10.0;   

    cout << x << endl;  //31

      

       return 0;

}

输出转换(C语言)

#include <stdio.h>

int main(void) {

       printf("%c\n", 255+50);  //305  ->  49 ('1');

       printf("%d\n", 255+50);  //305

       return 0;

}

int类型数据, 按照%f格式输出时,将得到错误的输出

float(或double) 类型数据,按照%d格式输出时,将得到错误的输出

 

强制类型转化

简单强制类型转换

(直接使用数据类型)

int x = 257 + 100;

cout << "x=" << x  << endl;  //357

     

x = (char)257 + 100; //100000001 -> 00000001

cout << "x=" << x  << endl;  //101

高级强制类型转换

  1. satic_cast
  2. dynamic_cast
  3. const_castt
  4. reinterpert_cast

(这个后面再详细介绍)

posted on 2022-10-16 09:57  会飞的鱼-blog  阅读(40)  评论(0)    收藏  举报  来源

导航