If m开发者_StackOverflowy application will require users to input whole numbers like 35, 44, 67, 90, is it okay to assign these values to a variable of data type float? Explain why or why not
Assigning an int
to a float
variable is basically OK for small values. However, according to the C# standard, float
values have only a precision of 7 digits. So, if the integer numbers are greater than 9 999 999, you will get rounding errors.
It's okay for small enough numbers to avoid rounding errors. It's okay for a few more, as for the first few where rounding errors happen they'll be cancelled out when rounding again.
However, why would you want to do this? The only effects are to add things that can go wrong (somehow that whole number isn't a whole number) and slow things down. While the efficiency difference between float and int is so small (for math, moving them around has the same efficiency for both as they're both the same size internally) that I would suspect anyone forcing integers to do a floating or decimal values job of premature optimisation (though not necessarily, indeed I have done it myself in some cases), forcing a float to do an integers job seems like premature pessimisation, unless there's somewhere in this where it actually acts as a float.
精彩评论