This question requires writing a program to calculate the sum of the sequence part 1 - 1/4 + 1/7 - 1/10 + ...
until the absolute value of the last item is not greater than the given precision eps
.
Input format:
Input gives a positive real number in one line eps
.
Output format:
In one line, sum = S
output the partial sum value in the format of " " S
, accurate to six digits after the decimal point. The title guarantees that the calculation result does not exceed the double precision range.
Input example 1:
4E-2
Output example 1:
sum = 0.854457
Input example 2:
0.02
Output example 2:
sum = 0.826310
Code:
# include <stdio.h>
# include <stdlib.h>
int main() {
double eps,sum = 0.0,value,sign = 1.0;
scanf("%lf",&eps);
int i = 1;
while(1) {
value = sign / i;
if (value < 0 && value + eps >= 0 || value > 0 && value - eps <= 0) {
sum += value;
break;
}else {
sign *= (-1);
i += 3;
sum += value;
}
}
printf("sum = %.6lf",sum);
return 0;
}
Submit screenshot:
Problem-solving ideas:
Similar to the previous difficulty and ideas, there is nothing left to say!