Explain this behavior of code? Why the floating point representation is giving the strange behavior. When the datatype is change

int j; j=2*3/4+2.0/5+8/5; printf("%d",j); float j; j=2*3/4+2.0/5+8/5; printf("%f",j);

2/13/2020 7:34:43 PM


3 Answers

New Answer


In first case j is int, so double part is going to be chopped of intermediate results j = 1 + 0.4 + 1; = (int) 2.4 2nd case j = 1 + 0.4 + 1 = (float) 2.4 = 2.4 remember 2*3/4 is int division and so is 8/5 In both case intermediate result is double but cast to int in first as j is int and cast to float in 2nd since j is float. Please do mention what do you expect from the code. Just saying explain the behavior is a question not different than one asked by a beginner to the programming as well as to the site and you are none of them.


~ swim ~ question edited thanks for the explanation. I'm beginner and floating point representation is always an headache. When I code something and get minor concept missing I would asked that to clear it that time but floating point and some c quizzes always get me in some doubts so I put question like explaining the strange behavior


int j; j = (int) (2*3/4+2.0/5+8/5); System.out.printf("%d\n",j); System.out.printf("int %d + double %.2f + int %d = int %d\n", 2*3/4, 2.0/5, 8/5, j); System.out.println(); float k; k = 2*3/4+2.0f/5+8/5; // k = (float) (2*3/4+2.0/5+8/5); System.out.printf("%f\n",k); System.out.printf("int %d + float %.2f + int %d = float %.02f\n", 2*3/4, 2.0f/5, 8/5, k);