首页 > 代码库 > Exercise 5.2 Summing 100 data values
Exercise 5.2 Summing 100 data values
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 result21 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。