求1+1/2+1/3+…+1/20?
#include <stdio.h> int main() { int i=1; double sum=0.0, t; while (i<=20) { t=1.0/i; sum=sum+t; i++; } printf("sum=%f\n", sum); return 0; }
再例:1/2-2/3+3/4-…+19/20
#include <stdio.h> int main() { int i=2; double sum=0.0, sign=1.0, t; while (i<=20) { t=sign*(i-1)/i; sum=sum+t; i++; sign=-sign; } printf("sum=%f\n", sum); return 0; }