编程一个程序:求1-1/2+1/3-1/4+....+1/99-1/100之值
时间: 2023-11-23 22:08:23 浏览: 225
C#求1-1/2+1/3-1/4+…….-1/100的值
以下是两种C语言编写的程序,用于求1-1/2+1/3-1/4+....+1/99-1/100之值:
方法一:
```c
#include <stdio.h>
int main() {
float i,j;
float sum=0,sum1=0,sum2=0;
for(i=1;i<=100;i+=2) {
sum1=sum1+1/i;
}
for(j=2;j<=100;j+=2) {
sum2=sum2+1/j;
}
sum = sum1 - sum2;
printf("sum=%.2f\n",sum);
return 0;
}
```
方法二:
```c
#include <stdio.h>
int main(){
double sum = 1.0;
for(int i=2;i<=100;i++){
if(i%2==0){
sum = sum - 1.0/i;
}else{
sum = sum + 1.0/i;
}
}
printf("%f",sum);
return 0;
}
```
阅读全文