4-1
#include<stdio.h> #include<math.h> int main(void) { int denominator,flag; double item,pi; flag=1; denominator=1; item=1.0; pi=0; while(fabs(item)>=0.0001){ item=flag*1.0/denominator; pi=pi+item; flag=-flag; denominator=denominator+2; } pi=pi*4; printf("pi=%.4f ",pi); return 0; }
4-2
#include<stdio.h> int main(void) { int count,num; double grade,total; num=0; total=0; count=0; printf("Enter grades:"); scanf("%lf",&grade); while(grade>=0){ total=total+grade; num++; if(grade<60) count++; scanf("%lf",&grade); } if(num!=0){ printf("Grade average is %.2f ",total/num); printf("Number of failures is %d ",count); } else printf("Grade average is 0 "); return 0; }
4-3
运行结果1
结果2
#include<stdio.h> int main(void) { int count,number; count=0; printf("Enter a number:"); scanf("%d",&number); if(number<0)number=-number; do{ number=number/10; count++; }while(number!=0); printf("It contains %d digits. ",count); return 0; }