码迷,mamicode.com
首页 > 其他好文 > 详细

Exercise 5.2 Summing 100 data values

时间:2014-12-19 12:53:02      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:c   value   val   su   values   exe   data   ci   at   

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     }

 

Exercise 5.2 Summing 100 data values

标签:c   value   val   su   values   exe   data   ci   at   

原文地址:http://www.cnblogs.com/xiaomi5320/p/4173620.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!