For() counter: getting float values
John Kauffman
Posts: 653
in Propeller 1
I need a loop where I can use these values in a calculation: 0.00, 0.01, 0.02, 0.03... 3.00.
I tried a float counter: fail.
I tried an integer counter for 0-300 then divided by 100: fail because int/int = int
It works as below with int counter then (float)int/100.
Is there an obviously better way to get that series of values?
- Thanks
int main()
{
int myInteger;
float myFloat;
for(myInteger=0;myInteger<=300;myInteger++)
{
myFloat = (float)myInteger/100;
print("\n%d %f",myInteger,myFloat);
}
}
I tried a float counter: fail.
I tried an integer counter for 0-300 then divided by 100: fail because int/int = int
It works as below with int counter then (float)int/100.
Is there an obviously better way to get that series of values?
- Thanks
int main()
{
int myInteger;
float myFloat;
for(myInteger=0;myInteger<=300;myInteger++)
{
myFloat = (float)myInteger/100;
print("\n%d %f",myInteger,myFloat);
}
}
Comments
You'll accumulate a slight error after 300 adds, but only you can determine if it's an acceptable tradeoff for your application.
Once you do this, another slight optimization would be to count down the integer counter (i=300; i>=0; i--) since it compiles to DJNZ, but it makes the code intent slightly less obvious to casual readers (comments are your friend !).
But John, your conclusion is definitely correct: on hardware without a floating point ALU, there is no good solution.
Now, based purely on the code you're showing, you don't actually need floating point.
I know, you probably just simplified the code significantly for the sake of posting - but it's good to drop this in here in case anyone else runs across it.