在线编译器 C

#include <stdio.h> float cosinus(float x) { float sum = 1; float term = 1; int n = 0; while (term >= 0.001 && term <= -0.001) ; { n = n + 2; term = -term * x * x / (n * (n - 1)); sum = sum + term; } return sum; } int main() { float degree; scanf("%f", &degree); float radian = degree * 3.14159265 / 180; printf("%.3f\n", cosinus(radian)); return 0; }
This code attempts to compute the cosine of an angle using a Taylor series expansion. The main function converts degrees to radians and calls the cosinus function, which is supposed to sum terms of the series until they become small. However, the loop does not work correctly.

- The while loop condition checks if term is both >= 0.001 and <= -0.001, which is impossible for any single value. This means the loop body never executes, and the semicolon after the while creates an empty loop body, so the block after it runs only once after the loop ends.
- The variable term is initialized to 1, which is larger than 0.001, so the loop should run, but the condition logic is flawed. You need to check the absolute value of term against the threshold, not both positive and negative limits simultaneously.