我與C語言的點滴(5)-迴圈(3)選擇
阿新 • • 發佈:2018-12-13
- 猜數字遊戲
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> void menu() { printf("****************************\n"); printf("********** 1.play **********\n"); printf("********** 0.exit **********\n"); printf("****************************\n"); } void game() { int random_num = rand() % 100 + 1; int input = 0; while (1) { printf("請輸入猜的數字:"); scanf("%d", &input); if (input > random_num) { printf("猜大了\n"); } else if (input < random_num) { printf("猜小了\n"); } else { printf("恭喜你,猜對了\n"); break; } } } int main() { int input = 0; srand((unsigned)time(NULL)); do { menu(); printf("請選擇:"); scanf("%d", &input); switch (input) { case 1: game(); break; case 0: printf("退出遊戲\n"); break; default: printf("選擇錯誤,請重新輸入!\n"); break; } } while (input); return 0; }
結果如下: 2. 在整型有序陣列中查詢想要的數字,找到了返回下標,找不到返回-1.(折半查詢) (二分查詢)
#include <stdio.h> #include <stdlib.h> int binary_search(int *arr,int key,int sz) { int left = 0; int right = sz - 1; while (left<=right) { int mid = left + (right - left) / 2; if (arr[mid] < key) { left = mid + 1; } else if (arr[mid] > key) { right = mid - 1; } else { return mid; } } return -1; } int main() { int arr[] = {1,2,3,4,5,6,7,8,9,10}; int k = 7; int sz = sizeof(arr) / sizeof(arr[0]); int ret = binary_search(arr, k, sz); if (-1 == ret) { printf("找不到\n"); } else { printf("找到了:%d\n", ret); } system("pause"); return 0; }
結果如下: 3. 模擬三次密碼輸入的場景 最多能輸入三次密碼,密碼正確,提示“登入成功”,密碼錯誤,可以重新輸入,最多輸入三次。三次均錯,則提示退出程式。
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { int i = 0; char password[20] = { 0 }; for (i = 0; i < 3; i++) { printf("請輸入密碼:"); scanf("%s", password); if (0 == strcmp(password, "123456")) //strcmp是字串比較函式,若s1、s2字串相等,則返回零;若s1大於s2,則返回大於零的數;否則,則返回小於零的數。 { break; } else { printf("密碼錯誤,請重新輸入!\n"); } } if (i < 3) { printf("登陸成功\n"); } else { printf("退出程式\n"); } system("pause"); return 0; }
結果如下:
- 編寫一個程式,可以一直接收鍵盤字元,如果是小寫字元就輸出對應的大寫字元,如果接收的是大寫字元,就輸出對應的小寫字元,如果是數字不輸出。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("請輸入一個字母:\n");
scanf("%c", &ch);
if (ch >= 'a'&&ch <= 'z')
{
ch = ch - 32;
printf("%c", ch);
}
else if (ch >= 'A'&&ch <= 'Z')
{
ch = ch + 32;
printf("%c", ch);
}
else
{
printf("輸入錯誤");
}
system("pause");
return 0;
}
結果如下: