Half-find search algorithm and binary search function and guessing number game implementation

折半找算法

#include<stdio.h> Int main() { Int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; Int left = 0; Int right = sizeof(arr) / sizeof(arr[0]) - 1; Int key = 7; Int mid = 0; While (left <= right) { Mid = (left + right) / 2; If (arr[mid] < key) { Left = mid + 1; } Else if (arr[mid]>key) { Right = mid - 1; } Else Break; } If (left <= right) Printf ("found, subscript is %d\n", mid); Else Printf("Not found\n");

    return 0;

}

二分找函数 Int bin_search(int arr[], int left, int right, int key) { Int mid = 0; While (left <= right) { Mid = (left + right) >> 1; If (arr[mid] < key) { Left = mid + 1; } Else if (arr[mid]>key) { Right = mid - 1; } Else Return mid; } Return -1; }

猜数字游戏游戏

#define_CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<time.h>

void menu() {     printf("###############################################################\n");     printf("####################    1. play   #############################\n");     printf("####################    2. exit   #############################\n");     printf("###############################################################\n"); }

void game() { Int random_num = rand() % 100 + 1; Int input = 0; While(1) { Printf ("Please enter the number guessed: \n"); Scanf("%d", &input); If (input > random_num) { Printf ("guess big \n"); } Else if (input < random_num) { Printf("Guess the small \n"); } Else { Printf ("Congratulations you guessed \n"); Break; } } }

int main() { Int input = 0; Srand((unsigned)time(NULL)); Do { Menu(); Printf("Please select:\n"); Scanf("%d", &input); Switch (input) { Case 1: Game(); Break; Case 2: Break; Default: Printf("Select error, please re-enter!\n"); } }

    while (input);     return 0; }