0
int decade;
float jeo;
PRINT("Enter Decade point =\r\n");
scanf("%d",&decade);
print_decimal(decade);
PRINT("\r\n");
jeo=(1/(1+decade));
PRINT("Decade point =");
print_decimal(jeo);//my function for showing floating point number.
PRINT("\r\n");

I have wrote this code in IAR embedded workbench software for ARM controller, but it's not giving me accurate answer, can anyone tell me why?? "when i am entering 3. it's giving me 0 answer".

mrflash818
  • 930
  • 13
  • 24
Ati
  • 43
  • 5
  • Integer division is the immediate issue. You also have a pole for decade being -1 which is undefined behaviour, although IEEE754 does define it. – Bathsheba Jan 07 '19 at 07:22
  • 2
    Possible duplicate of [Division result is always zero](https://stackoverflow.com/questions/2345902/division-result-is-always-zero) – phuclv Jan 07 '19 at 07:27
  • there are tons of duplicates [Dividing 1/n always returns 0.0](https://stackoverflow.com/q/13331054/995714), [Integer division always zero](https://stackoverflow.com/q/9455271/995714), [C++. Dividing 1 by any number gives 0](https://stackoverflow.com/q/13163964/995714)... – phuclv Jan 07 '19 at 07:28

3 Answers3

3

You are just doing your calculation with integer and assign afterwards to a float value. This will remove the digits after the decimal point.

Try this:

jeo=(1.0/(1.0+decade));
Mike
  • 4,041
  • 6
  • 20
  • 37
2

You are assigning the result of an integer division to jeo. In this case, if decade is any integer other than 0, the result of integer division will be 0. (Note: If decade is -1, you will have undefined behavior as a result of division by 0)

When the type after usual arithmetic conversions is an integer type, the result is the algebraic quotient (not a fraction), rounded in implementation-defined direction (until C99)truncated towards zero (since C99)

So make either the numerator or the denominator a float.

jeo=((float)1/float(1+decade);
P.W
  • 26,289
  • 6
  • 39
  • 76
  • 1
    instead of `(float)1` it'll be clearer to use `1.0f`. But in general doubles should be used unless you know you really need a float – phuclv Jan 07 '19 at 07:28
  • @phuclv: Agree. OP defined `jeo` as float. – P.W Jan 07 '19 at 07:32
  • @Ati: You are welcome. Check out this link as to what to do when your question is answered. https://stackoverflow.com/help/someone-answers – P.W Jan 08 '19 at 04:26
0

Try this

jeo=1/(1+float(decade));

this is because when trying to employ an integer in a logical expression like that, the result is calculated in integer first then converted to float. This procedure ,of course, removes the digits after the decimal point and adds artificial 0s.

Mostafa Ayaz
  • 480
  • 1
  • 7
  • 16