问题
Is there any compiler that has a directive or a parameter to cast integer calculation to float implicitly. For example:
float f = (1/3)*5;
cout << f;
the "f" is "0", because calculation's constants(1, 3, 10) are integer. I want to convert integer calculation with a compiler directive or parameter. I mean, I won't use explicit casting or ".f" prefix like that:
float f = ((float)1/3)*5;
or
float f = (1.0f/3.0f)*5.0f;
Do you know any c/c++ compiler which has any parameter to do this process without explicit casting or ".f" thing?
回答1:
If you don't like either of the two methods you mentioned, you're probably out of luck.
What are you hoping to accomplish with this? Any specialized operator that did "float-division" would have to convert ints to floats at some point after tokenization, which means you're not going to get any performance benefit on the execution.
回答2:
Any compiler that did what you want would no longer be a conforming C++ compiler. The semantics of integer division are well specified (at least for positive numbers), and you're proposing to change that.
It would also be dangerous since it would wind up applying to everything, and you might at some point have code that relies on standard integer arithmetic, which would silently be invalid. (After all, if you had tests that would catch that, you presumably would have tests that would catch the undesired integer arithmetic.)
So, the only advice I've got is to write unit tests, have code reviews, and try to avoid magic numbers (instead defining them as const float
).
回答3:
In C++ it's a bit odd to see a bunch of numeric values sprinkled through the code. Generally it is considered best practice to move any 'magic numbers' like these to their own static const float value, which removes this problem.
回答4:
No, those two options are the best you have.
来源:https://stackoverflow.com/questions/2449578/implicit-casting-integer-calculation-to-float-in-c