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

In this program j, a value of 2 is assigned.

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

but if the same expression is calculated using a calculator, it will be equal to 3.5, so in an integer expression it will become equal to 3.

I want to ask why is jassigned 2? What am I missing?

C:

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

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

-1
0
1
1
1
2
2
2
3
3
10
+4
source share
4 answers

Sort of:

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

2 * 3 / 4 Produce 1 -> it 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 2.

You need to order or say in another way that it is floating, 2 integers when dividing, produce an integer.

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

2 * 3 / 4and 8 / 5are whole divisions.

Using:

2 * 3 / 4.0and 8 / 5.0have floating point divisions.

+4

Analyze this step by step:

2*3/4 + 2.0 /5 + 8/5   // 8/5 gives 1, not 1.6 because it integer division

 6/4  +  0.4   + 1     // 2.0/5 is float division, so decimal place is left

 1    +  0.4   + 1     // 6/4 gives 1, not 1.5 because it integer division

        2.4

        2             //part after decimal point removed since j is int
+4
source
 2 * 3 / 4 + 2.0 / 5 + 8/5

*and /are calculated to +and -, which are given up to 3 steps:

  • integer calculation (since all operands are integer)

    2 * 3 / 4 = 6 / 4 = 1 
    
  • floating point calculation (since at least one operand is a floating point)

    2.0 / 5 = 2. / 5. = 0.4
    
  • integer calculation (since all operands are integer)

    8 / 5 = 1
    

Finally, the result from (1. and 2. and 3.) is equal to:

  1. floating point calculation (since at least one operand is a floating point)

    1. + 0.4 + 1. = 2.4
    

assigned to an integer (truncation down)

int j = 2.4

leads to j, equal to 2.

+2
source

All Articles