猜扑克牌大小问题二分法递归c语言源码
时间: 2024-09-26 14:06:03 浏览: 55
猜扑克牌大小的问题通常是一个经典的二分查找算法应用实例,在C语言中可以编写递归版本来解决。假设我们有一个有序数组代表扑克牌的大小,玩家需要猜测一张牌的位置。以下是简单的二分查找递归C语言代码示例:
```c
#include <stdio.h>
// 定义扑克牌数组,这里简化为0到9代表A到J
int cards[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// 二分查找函数,参数是目标值、数组首地址、数组长度
int binaryGuess(int target, int* arr, int low, int high) {
if (low > high) {
// 如果搜索范围为空,返回-1表示未找到
return -1;
}
int mid = (low + high) / 2; // 计算中间索引
// 比较目标值和中间元素
if (*arr[mid] == target)
return mid; // 找到了目标,直接返回
else if (*arr[mid] > target)
return binaryGuess(target, arr, low, mid - 1); // 目标小,搜索左半部分
else
return binaryGuess(target, arr, mid + 1, high); // 目标大,搜索右半部分
}
int main() {
int guess;
printf("请输入你猜测的扑克牌数字(0-9):");
scanf("%d", &guess);
int result = binaryGuess(guess, cards, 0, sizeof(cards) - 1);
if (result != -1)
printf("恭喜你,猜对了!牌的位置是 %d\n", result + 1);
else
printf("很遗憾,你猜错了,正确的牌是 %d\n", *cards);
return 0;
}
```
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)