练习:1.利用goto求和
1 #include <stdio.h>
2
3 int main(void)
4 {
5 int i = 0;
6 int sum = 0;
7
8 loop:
9 sum += i;
10 i++;
11
12 if (i < 10)
13 {
14 goto loop;
15 }
16
17 printf("sum = %d\ni = %d\n", sum, i);
18
19 return 0;
20 }
练习:1.从终端接收若干个数,以-1结束,计算所有输入数字的平均值
1 #include <stdio.h>
2
3 int main(void)
4 {
5 int num = 0;
6 int sum = 0;
7 int count = 0;
8
9 while (1)
10 {
11 scanf("%d", &num);
12
13 if (-1 == num)
14 {
15 break;
16 }
17
18 sum += num;
19 count++;
20 }
21
22 printf("Avg = %.3lf\n", (double)sum / count);
23
24 return 0;
25 }
练习:从终端接收10个数到数组中,计算这10个数的平均值
1 #include <stdio.h>
2
3 int main(void)
4 {
5 int a[10] = {0};
6 int i = 0;
7 int len = 0;
8 int sum = 0;
9
10 len = sizeof(a) / sizeof(a[0]);
11
12 for (i = 0; i < len; i++)
13 {
14 scanf("%d", &a[i]);
15 }
16
17 for (i = 0; i < len; i++)
18 {
19 sum += a[i];
20 }
21
22 printf("Avg = %.2lf\n", (double)sum / len);
23
24 return 0;
25 }
练习:从终端获得5个数到数组中,获得数组中的最小值
1 #include <stdio.h>
2
3 int main(void)
4 {
5 int a[5] = {0};
6 int i = 0;
7 int len = 0;
8 int min = 0;
9 int max = 0;
10
11 len = sizeof(a) / sizeof(a[0]);
12
13 for (i = 0; i < len; i++)
14 {
15 scanf("%d", &a[i]);
16 }
17
18 for (i = 1; i < len; i++)
19 {
20 if (a[min] < a[i])
21 {
22 min = i;
23 }
24 }
25 printf("min = %d\ni = %d\n", a[min], min);
26
27 for (i = 1; i < len; i++)
28 {
29 if (a[i] > a[max])
30 {
31 max = i;
32 }
33 }
34 printf("max = %d\ni = %d\n", a[max], max);
35
36 return 0;
1.冒泡排序:
1 #include <stdio.h>
2
3 int main(void)
4 {
5 int a[5] = {0};
6 int i = 0;
7 int j = 0;
8 int temp = 0;
9 int len = 0;
10
11 len = sizeof(a) / sizeof(a[0]);
12
13 for (i = 0; i < len; i++)
14 {
15 scanf("%d", &a[i]);
16 }
17
18 printf("Before : ");
19 for (i = 0; i < len; i++)
20 {
21 printf("%d ", a[i]);
22 }
23 printf("\n");
24
25 for (j = 0; j < len -1; j++)
26 {
27 for (i = 0; i< len - 1 - j; i++)
28 {
29 if (a[i] > a[i + 1])
30 {
31 temp = a[i];
32 a[i] = a[i + 1];
33 a[i + 1] = temp;
34 }
35 }
36 }
37
38 printf("After : ");
39 for (i = 0; i < len; i++)
40 {
41 printf("%d ", a[i]);
42 }
43 printf("\n");
44
45 return 0;
46 }