0
\$\begingroup\$

I'm using the ATMega128 micro for a project and CodeVisionAVR. It seems as if when I try a += with 2 floats, it doesn't calculate properly. For example, if I'm doing a PI loop for the integrator and do something like :

   float iTemp = 0;
   float countOffset = 0;
   iTemp += countOffset;

If I do that in my code, it gives very weird numbers that make no sense (expecting ~50, normally something like DC3D, but it changes everytime I print the numbers), I'm not even able to think of where they came from since they are inconsistant. My main question, are you allowed to use the += operator with floats?

*Side note: What about a ++ with a float?

\$\endgroup\$
12
  • 4
    \$\begingroup\$ Please post the weird numbers, which you have mentioned. Without those, the question is not quite complete. What are the inputs? What are the expected outputs? What are the actual outputs? \$\endgroup\$ – Nick Alexeev Sep 10 '15 at 19:13
  • \$\begingroup\$ So here is my actual code cut (hopefully pastebin works): pastebin.com/UuTUHVKm So I'm expecting a windup (should be slow, expecting values around 40-50). However I get values like D3CD. Whenever I print them, they always change. Also, they are initialized to zero. They are globals since it's an integrator accumulator. \$\endgroup\$ – biggi_ Sep 10 '15 at 19:17
  • 2
    \$\begingroup\$ @adeuerling Just edit the question. \$\endgroup\$ – Eugene Sh. Sep 10 '15 at 19:18
  • \$\begingroup\$ What?? You are printing them as hex?? Floats have a little meaning in their hex representation. \$\endgroup\$ – Eugene Sh. Sep 10 '15 at 19:22
  • \$\begingroup\$ Yup, it's not uncommon to print them in hex. Cuts code out converting to decimal. \$\endgroup\$ – biggi_ Sep 10 '15 at 19:22
4
\$\begingroup\$

1) float type is 32 bit long type, so if you really want to print it in hexadecimal representation, you should use the appropriate format specifier (or just examine the right number of bytes).
2) floats are usually represented in IEEE 754 format in memory, so the HEX representation is not directly translating to the actual float value, so it may seem random.
3) The arithmetical operators you have mentioned work just fine with floats.

*To find out the size of a type in bytes use the sizeof operator.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.