我是靠谱客的博主 热心板栗,这篇文章主要介绍C primer plus 第八章 练习5:,现在分享给大家,希望可以做个参考。

修改程序清单8.4中的猜测程序,使其使用更加智能的猜测策略,例如,程序最初猜50,让其询问
用户该猜大,小还是正确。如果该猜值小,则令下一次猜测值为50和100值,也就是75,如果75大,
则下一次猜测75与50之间的值等等,使用这种二分搜索策略,起码如果用户没有欺骗,该程序很快
会获得正确答案。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*#include <stdio.h> #include <windows.h> int main(void) { int guess = 50; int gue = 50; char xz; printf("Pick an integer from 1 to 100. I will try to guess it.n"); printf("Respond with a y if my guess is right and with an n if it is wrong.n"); printf("Uh...is your number %d?n", guess); while ((xz = getchar()) != 'y') { switch (xz) { case 'd':gue = (0 + gue) / 2; printf("%dn", gue); break; case 'x':gue = (gue + 100) / 2; printf("%dn", gue); break; default: break; } } printf("I knew I could do it!n"); system("pause"); return 0; }*/

以上程序还是有瑕疵。。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdio.h> #include <windows.h> int main(void) { int low, high, mid; low = 1, high = 100, mid = 50; char xz; printf("Pick an integer from 1 to 100. I will try to guess it.n"); printf("Respond with a y if my guess is right and with an n if it is wrong.n"); printf("输入'q'退出,请输入'd'表明此数太大了,或'x'表明此数太小了: n"); printf("Uh...is your number %d?n", mid); while ((xz = getchar()) != 'q' && low < high) { if(xz == 'y'){ printf("正确!n"); }else if (xz == 'd') { printf("太大了吧!n"); high = mid - 1; }else if(xz == 'x') { printf("太小了吧!n"); low = mid + 1; } mid = (high + low) / 2; printf("是%d吗,太大输入d,太小输入x,正确输入y。n", mid); while ((xz = getchar()) != 'n') { continue; } } printf("I knew I could do it!n"); system("pause"); return 0; }

最后

以上就是热心板栗最近收集整理的关于C primer plus 第八章 练习5:的全部内容,更多相关C内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部