Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the value of j in "j= 2 * 3 / 4 + 2.0 / 5 + 8/5;" set to 2 and not 3?

In this program, j is assigned the value 2

j = 2 * 3 / 4 + 2.0 / 5 + 8/5;

but if same expression is calculated with calculator it will come be 3.5 so in integer it will become 3.

I want to ask why j is assigned to 2? What am I missing?

C program:

#include <stdio.h>
int main()
{
    int i,j,k=0;
    int line=0;
    j = 2 * 3 / 4 + 2.0 / 5 + 8/5;
    printf(" %d --------- \n", j);
    k -= --j;
    printf(" %d --------- \n", k);
    for(i=0;i<5;i++)
    {
        switch(i+k)
        {
        case 1:
        case 2:
            printf("\n %d", i+k);
            line++;
        case 3:
            printf("\n %d", i+k);
            line++;
        default:
            printf("\n %d", i+k);
            line++;
        }
    }
    printf("\n %d", line);
    return 0;
}

Output is:

2 --------- 
-1 --------- 

-1
0
1
1
1
2
2
2
3
3
10
like image 490
Linkon Avatar asked Dec 08 '22 04:12

Linkon


1 Answers

Something like:

j= 2 * 3 / 4 + 2.0 / 5 + 8/5;

2 * 3 / 4 Produce 1 -> it's integer
2.0 / 5 Produce 0.4 -> float
8/5 Produce -> 1.6 -> but in integer 1

Sum: 1 + 0.4 + 1 -> 2.4 -> converted to integer it's 2.

You have to typecast or say in other way it's float, 2 integers at dividing, produce integer.

like image 50
Danijel Avatar answered Feb 16 '23 04:02

Danijel