0

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):

  • a = 1/(1/10 + 1/100) = 9.09

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)?

Suvi_Eu
  • 255
  • 1
  • 3
  • 16

2 Answers2

3

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • You have reason doing #include double a = 0.0; int b = 100; int main() { a = 1.0/(1.0/10.0 + 1/(float)b) + 0.15; b = a; a *= 10; if ((a - b*10)>5) b++; printf("float: %f , int: %i",a,b); return 0; } is fixed. Thanks. – Suvi_Eu Apr 08 '19 at 10:48
1

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 floats and not doubles, as the support can be different.

unwind
  • 391,730
  • 64
  • 469
  • 606