Exercise 5-2. Define an array, data, with 100 elements of type double. Write a loop that
will store the following sequence of values in corresponding elements of the array:
1/(2*3*4) 1/(4*5*6) 1/(6*7*8) ... up to 1/(200*201*202)
Write another loop that will calculate the following:
data[0] - data[1] + data[2] - data[3] + ... -data[99]
Multiply the result of this by 4.0, add 3.0, and output the final result. Do you recognize the
value you get?
1 //Exercise 5.2 Summing 100 data values 2 #include <stdio.h> 3 4 int main(void) 5 { 6 double data[100]; // Stores data values 7 double sum = 0.0; // Stores sum of terms 8 double sign = 1.0; // Sign - flips between +1.0 and -1.0 9 size_t i = 0; 10 11 int j = 0; 12 for( i = 0 ; i < sizeof(data)/sizeof(double) ; ++i)//神马意思? 13 { 14 j = 2*(i + 1); 15 data[i] = 1.0/(j * (j + 1) * (j + 2)); 16 sum += sign*data[i]; 17 sign = -sign; 18 } 19 20 // Output the result 21 printf("The result is %.4lf\n", 4.0*sum + 3.0); 22 printf("The result is an approximation of pi, isn‘t that interesting?\n"); 23 return 0; 24 }
时间: 2024-10-16 11:27:28