编程实现序列 s=1/2-1/9+1/16-1/23+1/30-1/37……共累加n项,n由键盘输入赋值。c语言
时间: 2023-11-16 18:06:10 浏览: 430
浙大-Java语言程序的设计编程答案6.doc
这是一个关于计算序列 s=1/2-1/9+1/16-1/23+1/30-1/37……前n项和的问题。下面是C语言的三种实现方式:
1.使用while循环实现:
#include <stdio.h>
int main() {
int num = 1, s = 1, t= 1;
double sum = 1.00;
int n;
printf("请输入n的值:");
scanf("%d", &n);
while (num <= n) {
s = -s;
t = t + 7;
sum += ((double) s / t);
num++;
}
printf("前%d项和=%0.3f", n, sum);
return 0;
}
2.使用for循环实现:
#include <stdio.h>
int main() {
int i, s = 1, t = 1;
double sum = 1.00;
int n;
printf("请输入n的值:");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
s = -s;
t = t + 7;
sum += ((double) s / t);
}
printf("前%d项和=%0.3f", n, sum);
return 0;
}
3.使用函数进行封装:
#include <stdio.h>
double getsum(int n) {
int s = 1, t = 1;
double sum = 1.00;
for (int i = 1; i <= n; i++) {
s = -s;
t = t + 7;
sum += ((double) s / t);
}
return sum;
}
int main() {
int n;
printf("请输入n的值:");
scanf("%d", &n);
printf("前%d项和=%0.3f", n, getsum(n));
return 0;
}
阅读全文