Arduino inability to calculate numbers correctly! Why?

Hey Guys,

This is a simple code
Why can't Arduino calculate correctly?
I even tried different computational variables but it did not work.

long a=99999999;
long b=100;
float c=a*b;
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
Serial.println(c);
}

void loop() {
  // put your main code here, to run repeatedly:

}

I even tested two Arduino board models, one UNO and the other Pro Micro, but the answers were wrong.
What exactly should I do?

What did you expect and what did you get?

Float is only 32 bits, with only 6-7 digits of precision: float - Arduino Reference

1 Like

Thats easy.

Tell the forum why you think the answers are wrong.

99999999 is a 27 bit binary number.
Multiply that by 100, and it becomes a 33 bit number.
Now imagine representing that number accurately in 32 bits.
(This isn't a troubleshooting or installation issue)

1 Like

Pilot and posting error.

1 Like

Try

   float c = (float)a*b;

Then your print will probably give you "ovf" :slight_smile:
(but the value will be usable in subsequent calculations. With some loss of precision.)

For example:

long a=888888888;
long b=100;
float c=(float)a*b;
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
Serial.println(c/10000.);
}

Will print 8888889.00

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.