Exceed the int type data range, use double type high precision

First topic: Calculation**1! + 2! + 3! +… + 20! = **

 int i , j ;
 double sum = 0 , amass = 1 ; //每一项积
 for( i = 1 ; i <= 20 ; i++ )
 {
    
    
  for( j = 1 ; j <= i ; j++ )
  {
    
    
   amass = amass * j ;
  }
  sum =  sum + amass ;
  amass = 1 ;
 }
/*或者
 for ( i = 1 ; i <= 20 ; i++ )
 {
  amass =  amass * i ;
  sum = sum + amass ;
    
 }
 */
  printf( "1阶...20阶的和为%22.15e\n" , sum ) ;

The result is:
Insert picture description here
Why do sum and amass use the double type here?
Answer: Because in VC++6.0 int and long type data occupies 4 bytes in the memory, the data range is from 2.1 billion to 2.1 billion, which cannot accommodate the result. Therefore, it is defined as a double type to improve accuracy.

Guess you like

Origin blog.csdn.net/angelsweet/article/details/104277836