简体   繁体   中英

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 . 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 ).

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. 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.

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. 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. Here a could be same as your expression (i+j)/2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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