简体   繁体   English

为什么要打字?

[英]why do we type-cast?

If I do: 如果我做:

int i=3, j=10;
float f;
f=(i+j)/2;
so f won't get value 6.5 but 6.

But, 但,

f=(i+(float)j)/10;//edited 

would be f=6.5 . 将为f=6.5 What is the place where this temporary values are stored and why do we need to type-cast? 此临时值的存储位置是什么?为什么要强制转换?

f=(i+j(float))/10;

is incorrect; 是不正确的; the type in a cast comes before its operand: 类型转换的类型位于其操作数之前

f=(i+(float)j)/10;

Anyway. 无论如何。 When evaluating an arithmetic operator, if one operand is of a floating point type and the other is of an integer type, then the integer operand is converted to the floating point type and floating arithmetic is performed. 在评估算术运算符时,如果一个操作数是浮点类型,而另一个是整数类型,则将整数操作数转换为浮点类型并执行浮点运算。

This is part of what are called the usual arithmetic conversions (you can find out more about those by searching Google, though MSDN has a simple explanation of what they are ). 这是所谓的普通算术转换的一部分 (您可以通过搜索Google来找到更多有关这些的信息,尽管MSDN对其进行了简单的解释 )。

Where the temporary value is stored depends on the compiler and the computer. 临时值的存储位置取决于编译器和计算机。 It's likely to be stored in a register since you're going to use it immediately, but it could be stored on the stack or somewhere else. 由于您将立即使用它,因此它很可能存储在寄存器中,但也可以存储在堆栈中或其他地方。

C defines "integral promotion" rules which determine what type will be used to carry out an integer calculation. C定义了“积分提升”规则,这些规则确定将使用哪种类型来执行整数计算。 An integer expression will be promoted to a type big enough to hold all values of the types in the expression, signed if possible, else unsigned. 整数表达式将提升为足够大的类型,以容纳表达式中所有类型的值,如果可能的话,请签名,否则为无符号。 By casting one of the values to float you force the compiler to do floating-point promotion which promotes all of the integers to a suitable floating point type. 通过将值之一强制转换为浮点数,您可以强制编译器进行浮点升级,从而将所有整数提升为合适的浮点类型。 You could also write 0.1 * (i+j) in which case i+j would be computed as an integer and then promoted to a floating point type to multiply with 0.1. 您还可以编写0.1 * (i+j)在这种情况下, i+j将被计算为整数, 然后提升为浮点类型以乘以0.1。

f=(i+j)/2 will give integer value because in RHS i,j,2 they all are integer thus result will be stored in the form of integer. f =(i + j)/ 2将给出整数值,因为在RHS i,j,2中它们都是整数,因此结果将以整数形式存储。 for example 例如

 int a;
            float b;
            b=a;

there b will store only the integer value of a even if computed value of a is float. 即使a的计算值是浮点型的,b也将仅存储a的整数值。 Here a could be same as your expression (i+j)/2. 这里a可以与您的表达式(i+j)/2.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM