Reputation: 275
I have wrote an algorithm for MCU that executes the expression of two paralel Resistances before doing more calculations with the division result. When debugging the values had no sense; they were too much big and float var did not update their initial value.
So I went to https://www.onlinegdb.com/ and I tried a part of my algorithm there. When execute the code it launches a non normally exiting with the arithmetic exception at line:
a = 1/(1/10 + 1/b) + 0.15;
First I was working with float but I have thought that exception could be caused by an overflow, hence I did the variable storage bigger using double, but the same exception appears. Then I tried doing the same but saying:
a = (1/10 + 1/b) + 0.15;
and the execution worked!
So, I have seen the '1' operator was the cause. But I don't understand exactly why and how to fix it (without using math.h).
The code is this:
#include <stdio.h>
float a = 0.0;
int b = 100;
int main()
{
a = 1/(1/10 + 1/b) + 0.15;//Req
b = a; //get int part
a *= 10;//fractionary part converted to dec
if ((a - b*10)>5) b++;
printf("float: %f , int: %i",a,b);
return 0;
}
I was expecting to get (debugging):
which I think is not a big value to fit in a float or a double var. Instead of this I get the exception.
How to work with floats/doubles and int values to avoid exceptions when 1/(something smaller)?
Upvotes: 0
Views: 64
Reputation: 399871
This:
a = 1/(1/10 + 1/b) + 0.15;//Req
is doing integer division in the first part, since 1
and 10
are both of type int
. You meant:
a = 1.f / (0.1f + 1.f / b) + 0.15f;
especially for embedded targets, it can be quite important to make sure your literals are float
s and not double
s, as the support can be different.
Upvotes: 1
Reputation: 409196
Both 1/10
and 1/b
are integer expressions, which both result in the integer 0
.
So you have a plain division by zero error.
Solve it by using e.g. 1.0f
as the dividend, like 1.0f / (0.1f + 1.0f / b) + 0.15f
.
Upvotes: 3