type casting int float

1
2
int foo(43), goo(23);
result = static_cast<float>(foo/goo); !!integer label persists


 
result = static_cast<float>(float(foo)/goo); !!works float cast


Is the reason the second works is that an explicit conversion to foo thereby triggers the conversion of goo to float as well?
closed account (E3h7X9L8)
in the
result = static_cast<float>(foo/goo); the foo/goo expression is done first that means the result is int because both are int , after the expression is calculated , only then the cast makes the foo/goo result a float type, you could do

static_cast<float>(foo)/goo this code makes goo float then divides it by goo which is legal and the result is indeed of type float

edit: the second piece of code you provided could be considered equivalent to
static_cast<float>(static_cast<float>(foo)/goo)
Last edited on
ok...but the conversion to float in (foo)/goo is implicit, right? If it is why is it further clarified in <float>?

Thx in advance.
ok...but the conversion to float in (foo)/goo is implicit, right?


No, as leryss was saying the division is done first, seen as they are both int it's integer division, then it's cast to float, giving the wrong answer.

By explicitly casting one of the numbers to float first, the division is now float division (the compiler casts both of them to float)- giving the right answer.

Btw, double is the preferred type rather than float. Some graphics libraries use float exclusively, unless you are doing that or have some other very good reason, prefer double.

The reason for this is that float only has 6 or 7 significant digits, so it's precision is easily exceeded. double has 15 or 16 significant digits so that is much better, and suitable for most things.
float is a primitive type. use c cast is enough , double is better than float but takes twice the size. foo and goo can be just float so no need for casting . Since they are small numbers dont take a double for these
Since they are small numbers dont take a double for these


It's not going to matter, unless there are billions of them.

As I said the precision of a float is easily exceeded, so best to make them double and not worry about that.

An example of exceeding precision:

Say we need 3 dp for our numbers, a float might have 6 significant figures, so that only leaves 3 more figures, which gives a max for out number of 999.999. If our numbers in a container are about 50.0, we can only have 20 numbers before we loose precision on the sum of those numbers. Not to mention squaring and square roots, reciprocals etc.

If we were to choose double (15sf) in the same scenario, our sum could be 9.99999999999999e12 , which is clearly much better.

Using c style casts aren't recommended either.

So foo is extrinsically cast to float, then goo is intrinsically promoted to float.

float / int => float / float = float

Will be using double for precision but wanted to do float as a thought exercise.
Topic archived. No new replies allowed.