有点标题党的意思了,呵呵,先把有问题的程序罗列一下,再说说遇到的问题:
[root@LinServer c-study]# cat -n eat_hamberger.c
1 #include
2 void
3 eat_hamberger (int x)
4 {
5 int i;
6 for (i = 1; i <= x; i++)
7 {
8 if (i == 1)
9 printf ("now , I have eat %d hamberger !\n", i);
10 else
11 printf ("now , I have eat %d hambergers !\n", i);
12 }
13 }
14
15 int
16 hungry ()
17 {
18 int is_hungry;
19 while (1)
20 {
21 printf ("are you hungry? [0|1] \n");
22 is_hungry = scanf ("%d", &is_hungry);
23 if (is_hungry != 0 && is_hungry != 1)
24 {
25 printf ("input error! \n");
26 continue;
27 }
28 else
29 break;
30 }
31 if (is_hungry == 0)
32 return 0;
33 else
34 return 1;
35
36 }
37
38 int
39 main (void)
40 {
41 int how_many;
42 if (hungry () == 1)
43 {
44 while (1)
45 {
46 printf ("how many hambergers do you want to eat ? [1-100]\n");
47 how_many = scanf ("%d", &how_many);
48 if (how_many >= 1 && how_many <= 100)
49 {
50 eat_hamberger (how_many);
51 break;
52 }
53 else
54 {
55 printf ("input error! \n");
56 continue;
57 }
58 }
59
60 }
61
62 return 0;
63
64 }
修改之后的是:
[root@LinServer c-study]# cat -n eat_hamberger_version2.c
1 #include
2 void
3 eat_hamberger (int x)
4 {
5 int i;
6 for (i = 1; i <= x; i++)
7 {
8 if (i == 1)
9 printf ("now , I have eat %d hamberger !\n", i);
10 else
11 printf ("now , I have eat %d hambergers !\n", i);
12 }
13 }
14
15 int
16 hungry ()
17 {
18 int is_hungry;
19 printf ("are you hungry? [0|1] \n");
20 if (scanf ("%d", &is_hungry) ==1)
21 while (is_hungry != 0 && is_hungry != 1)
22 {
23 printf ("input error! \n");
24 scanf ("%d", &is_hungry);
25 }
26
27 if (is_hungry == 1)
28 return 1;
29 else
30 return 0;
31
32 }
33
34 int
35 main (void)
36 {
37 if (hungry () == 1)
38 {
39 printf ("how many hambergers do you want to eat ? [0-9]\n");
40 int how_many;
41 how_many = getchar ();
42 while (how_many < '0' || how_many > '9')
43 {
44
45 printf ("input error! please reinput \n");
46 how_many = getchar ();
47
48 }
49 eat_hamberger (how_many);
50
51 return 0;
52
53 }
54 }
这个小例子主要是熟悉c的语句,其他的scanf输入,getchar输入等是有bug的,这个先不仔细管了,先搞好if、while,for等等这些语句是重要的。
阅读(492) | 评论(0) | 转发(0) |