-2

I have tried several to identify why, but I could not do so, so if anyone get identified please let me know..

#include <stdio.h>
    
int main()
{
    int i,n=1;
    float div=0,sum=0,j=1;
    for(i=1;i<=7;i++)
    {
        j=1;
       for(n=1;n<=i;n++)
       {
           j=j*n;
       }
    div=i/j+div;
    
    }
    printf(" %f",div);

    return 0;
}

actually it is a program to display " Write a program to add first seven terms of the following series using For-Loop :

(1/1!)+(2/2!)+(3/3!)+…………  "      

By running the above program we get result as 2.72 which is correct one. but if we run code below

#include <stdio.h>

int main()
{
    int i,n=1,j=1;
    float div=0,sum=0;
    for(i=1;i<=7;i++)
    {
        j=1;
       for(n=1;n<=i;n++)
       {
           j=j*n;
       }
    div=i/j+div;
    
    }
    printf(" %f",div);

    return 0;
}

but what actually done is changing j=1 from int to float and vice versa. but the result is varying..

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    `i/j` if both of those are of `int` type then the result is an `int` with the decimal part truncated away. – kaylum Sep 23 '20 at 12:25

2 Answers2

0

you cant divide by integer and expect a float answer, you can cast j to float as follows:

div = i / (float)j + div;

which will give you the answer you want

Mansoor
  • 2,357
  • 1
  • 17
  • 27
YosefAhab
  • 64
  • 10
  • very thank you for your answer, it really helped me a lot..!, But one thing if we declare (float) near a int value does it become a float value?and similarly if we declare a (char) near a int value does it display ASCII value – Dharniesh P R Sep 24 '20 at 15:59
  • @DharnieshPR yep! [read more](http://www.cplusplus.com/doc/tutorial/typecasting/) – YosefAhab Sep 24 '20 at 19:49
0

It makes a difference here:

div=i/j+div;

When the / operator is evaluated in the second piece of code, both operands have type int so integer division is performed which truncates any fractional part. When j is declared as type double, floating point division is performed and no truncation occurs.

dbush
  • 205,898
  • 23
  • 218
  • 273