C语言编程小练习2
2.1输入一行字符,统计英文字母、数字字符、空格和其他字符个数。(此题统计不确定数目的字符,用while循环更合适,且以回车键结束输入。)
1 #include<stdio.h>
2
3 int main(void)
4 {
5 char ch;
6 int i, a, b, c, n ;
7 a = b = c = n = 0;
8 printf("Please input some characters ending with key ENTER:\n");
9 scanf("%c", &ch);
10 while (ch != '\n') {
11 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
12 a++;
13 else if (ch >= '0' && ch <= '9')
14 b++;
15 else if (ch == ' ')
16 c++;
17 else
18 n++;
19 scanf("%c", &ch);
20 }
21 printf("letters = %d\n", a);
22 printf("numbers = %d\n", b);
23 printf("spaces = %d\n", c);
24 printf("others = %d\n", n);
25
26 return 0;
27 }
2.2求1 - 1/2 +1/3 - 1/4 +…… −1n+1 − 1 n + 1 /n的值,绝对值小于 10−5 10 − 5 的项不计算。(以下用了几种变例)。
//方法一、while 循环,使用用pow函数,科学计数法,double类型声 明
2 #include<stdio.h>
3 #include<math.h>
4
5 int main(void)
6 {
7 int n = 1;
8 double i;
9 double sum = 0;
10 while(n < 1.0e5 + 1) {
11 i = pow(-1,n+1);
12 sum += i / n;
13 n++;
14 }
15 printf("%lf\n", sum);
16 return 0;
17 }
//方法二、while循环,使用用pow函数,十进制,且float类型声明(不推荐)
19 #include <stdio.h>
20 #include <math.h>
21 int main(void)
22 {
23 float sum=0.0;
24 int a;
25 int i=1;
26 while (i<100001)
27 {
28 a=pow(-1,i+1);
29 sum=sum+(a*(1.0/i));
30 i++;
31 }
32 printf("sum = %f\n",sum);
33 return 0;
34 }
35
//方法三、for循环,少许修改,double类型声明
37 #include<stdio.h>
38
39 int main(void)
40 {
41 double sum = 0;
42 double a;
43 int t = 1;
44
45 for(int i = 1;i <= 100000; i++)
46 {
47 a = (double)t / i;
48 t = -t;
49 sum += a;
50 }
51 printf("%f\n",sum);
52 return 0;
53 }
//也不算方法四,while循环少许简化
55 #include<stdio.h>
56
57 int main(void)
58 {
59 int n = 1, t = 1;
60 double sum = 0;
61 while (n < 1.0e5 + 1) {
62 sum += t * ( 1.0 / n);
63 n++;
64 t = -t;
65 }
66 printf("sum = %lf", sum);
67 return 0;
68 }
2.3根据公式π4≈1−13+15−17+⋯求π的近似值,绝对值小于10−5的项不计算。 2.3 根 据 公 式 π 4 ≈ 1 − 1 3 + 1 5 − 1 7 + ⋯ 求 π 的 近 似 值 , 绝 对 值 小 于 10 − 5 的 项 不 计 算 。
1 #include<stdio.h>
2
3 int main(void)
4 {
5 int a = 1, t = 1;
6 double sum = 0;
7 while (a < 1.0e5 + 1) {
8 sum += t * (1.0 / a );
9 t = -t;
10 a += 2;
11 }
12 printf("%lf", sum);
13 return 0;
14 }
2.4输出所有的水仙花数。水仙花数是一个三位正整数,每位数字的三次方之和等于该数本身。例如: 13+53+33=153, 1 3 + 5 3 + 3 3 = 153 , 即153是水仙花数。
1 #include<stdio.h>
2
3 int main(void)
4 {
5 int i, a, b, c;
6 for ( i = 100; i <= 999; i++) {
7 a = i % 10;
8 b = i / 10 % 10;
9 c = i / 100;
10 if ( a*a*a + b*b*b + c*c*c == i )
11 printf("%6d", i);
12 }
13 printf("\n");
14 return 0;
15 }