C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
C预处理器

Type Casting VS Type Conversion

程序中使用了两个术语类型转换和类型转换将一种数据类型转换为另一种数据类型。只有当编译器彼此兼容时,才可以进行数据类型的转换。让我们讨论任何编程语言中类型转换和类型转换之间的区别。

什么是类型转换?

当一种数据类型转换为另一种数据类型时由程序员或用户在编写任何编程语言的程序代码时所使用的机制称为类型转换。程序员手动使用它将一种数据类型转换为另一种数据类型。如果我们要将目标数据类型更改为另一种数据类型,则使用它。请记住,目标数据类型必须小于源数据类型。因此,这也称为缩小转换。
类型转换与类型转换之间的差异
语法:
Destination_datatype = (target_datatype) variable;
(data_type) it is known as casting operator
Target_datatype: 这是我们要转换目标数据类型的数据类型。该变量定义了一个将以target_data类型转换的值。让我们通过一个示例来理解类型转换的概念。
假设,我们想将 float 数据类型转换为 int 数据类型。在此,目标数据类型小于源数据,因为 int 的大小为2个字节,而 float 数据类型的大小为4个字节。当我们更改它时,float变量的值将被截断并转换为整数变量。可以使用兼容和不兼容的数据类型进行投射。
float b = 3.0;
int a = (int) b; // converting a float value into integer
让我们了解通过C程序进行的类型转换。
AreaOfRectangle.c
#include<stdio.h>
#include<conio.h>
void main()
{
  printf("\n Welcome to lidihuo tutorials ");
  float x = 3.5, y = 4.5;  // the size of float variable is 4 byte.
  int area; // the size of the int variable is 2 bytes.
  area = (int) x * y; // after conversion the product converts into integer
  printf("\n Area of a Rectangle is : %d", area);
  printf("\n Here, we convert float data type into the int data type");
  getch();
}
输出:
类型转换与类型之间的差异Conversion

什么是类型转换?

如果在编译时将一种数据类型自动转换为另一种数据类型,则称为类型转换。如果两种数据类型彼此兼容,则由编译器执行转换。请记住,目标数据类型不应小于源类型。也称为数据类型的扩展转换。
类型转换和类型转换之间的区别
让我们通过一个示例来理解类型转换。
假设我们有一个 int 数据类型,并且想要将其转换为浮动数据类型。这些是彼此兼容的数据类型,因为它们的类型是数字,并且int的大小为2个字节,小于float数据类型。因此,编译器会自动转换数据类型,而不会丢失或截断值。
int a = 20;
float b; 
b = a; // Now the value of variable b is 20.000   /* It defines the conversion of int data type to float data type without losing the information. */ 
在上面的示例中,将int数据类型转换为float类型,其大小比int更大,因此扩展了源数据类型。
让我们通过C理解类型转换。程序。
#include<stdio.h>
#include<conio.h>
void main()
{
  printf("\n Welcome to lidihuo tutorials ");
  int x = 3, y = 4;  // the size of int variable is 2 byte.
  float area; // the size of float variable is 4 bytes.
  area =  x * y; /* It is a type conversion that automatically converted by the compiler at the compile time of a program. */
  printf("\n Area of a Rectangle is : %f", area);
  printf("\n Here, we convert int data type to the float data type");
  getch();
}
输出:
类型转换与类型之间的差异Conversion

类型转换与类型转换之间的区别

S.N。 类型转换 类型转换
1 类型转换是一种机制,程序员可以使用cast()运算符将一种数据类型转换为另一种数据类型。 类型转换允许编译器在程序或代码的编译时将一种数据类型转换为另一种数据类型。
2 既可以使用兼容的数据类型,也可以使用不兼容的数据类型。 类型转换仅与兼容的数据类型一起使用,因此不需要任何强制转换运算符。
3 它要求程序员手动将一个数据转换为另一种类型。 不需要任何程序员干预就可以将一种数据类型转换为另一种数据类型,因为编译器会在程序运行时自动对其进行编译。
4 在程序员设计程序时使用。 它在程序编译时使用或发生。
5 将一种数据类型转换为另一种数据类型时,目标数据类型必须小于源数据。 将一种数据类型转换为另一种数据类型时,目标类型应大于源数据类型。
6 这也称为缩小转换,因为一种较大的数据类型会转换为较小的数据类型。 这也称为扩展转换,因为一种较小的数据类型会转换为较大的数据类型。
7 更可靠,更有效。 效率较低,可靠性较低。
8 类型转换中可能会丢失数据或信息。 在类型转换中,从小型数据类型转换为大型数据类型时,数据不太可能丢失。
8
float b = 3.0;
int a =(int)b 
 int x = 5,y = 2,c;
float q = 12.5,p;
p = q/x; 

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4