This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
I have a really basic question here and it has been driving me up the wall all day .....how do I populate an array with values between 500 and 3000 with increments of 0.05?
I have tried the following:
The current error I get with the above code is that I cannot convert from float to int for the iterator 'i'. I have tried umpteen different variants of the above code but to no avail.
i am sure I am making a small error here and I appreciate any help given.
Your index starts at 0 and increments with 1. If you could have declarations of different types in a for loop you would want the following:
You will need to move the declaration of either i or f outside the for-loop. Alternatively, you could drop f completely and recalculate its value each time:
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Feb 10, 2010
note that you will quickly get rounding errors...
Is there anyway to eliminate this round off error?
When I compiled the code, my maximum value went up to 3256.2 rather than 3000....I presume the round-off error is to blame for this?
Joined: Feb 10, 2010
Sorry, I was mistakingly using different values there and I do get a value of in and around 3000 (2999.95) to be exact. But my question still stands about eliminating the roundoff error, is it possible?
First, figure out how big the array should be. You were close with (end-start)/step. The answer should be an integer. Hint: suppose the end was 501 instead of 3000. Second, make a short list on a piece of paper, the index and the value to place at the index, like this:
Then figure out the formula for the value when the index is given.
Then write the code, a for loop with the integer index and the end point you calculated, and a body of one assignment with the formula you figured out.
(edited to change 50 to 500.)