Thursday, July 16, 2015

What is the behavior of integer division in C++


I tried out this snippet

#include <stdio.h>                                                                                                                                                                                                                                                                                                        
int main()                                                                                                                                                   
{                                                                                                                                                                                                                                                                                                                                    
  int median1 = (8+9)/2;                                                                                                                            
  int median2 = (8+8)/2;                                                                                                                              printf("median1 %d median2 %d \n", median1, median2);                                                                                                                                                                                                                                        
  int median3 = (int)(8+9)/2;                                                                                                                     
  printf("median3 %d \n", median3);                                                                                                         
  return 0;                                                                                                                                                   
}                                                                                                                                                                 

The value for median1, median2 and median3 was 8

Will the result always be floor of the division ?
The answer is yes

C and C++ seem to truncate the fraction part of the quotient

No comments:

Post a Comment