用for循环,第二个数就为负数第三个负负为正依次推类。
int main() {
int sign = 1;
double sum = 0.0;
int deno =1;
for (int deno = 1; deno <= 100; deno++) {
double term = sign * (1.0 / deno);
sum+= term;
sign = -sign;
}
printf("结果为:%f\n", sum);
return 0;
}
if循环(奇数偶数)
#include<stdio.h>
int main() {
double sum_odd = 0.0;
double sum_even = 0.0;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 1) {//取模为1时奇数else否则为偶数
sum_odd += 1.0 / i;
} else {
sum_even += 1.0 / i;
}
}
double result = sum_odd - sum_even;
printf("结果为:%f\n", result);
return 0;
}
求1加到到某某1/n时或者1加n啊之类的。
#include<stdio.h>
int main() {
int n=0;
double sum = 0;
printf("请输入n:");
scanf_s("%d", &n);
for (int i = 1; i <= n; i++) {
sum += 1.0 / i;//sum=sum+几分之一
}
printf("sum:%.3f\n", sum);//小数点后三位
return 0;
}
对了还有其他方法欢迎大家补充
标签:int,double,sum,C语言,deno,0.0,100,main,+......- From: https://blog.csdn.net/2301_81990803/article/details/136902958