C語言入門五
阿新 • • 發佈:2018-10-31
1.猜數字遊戲
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<time.h> void Menu(){ printf("****************************\n"); printf("**********1.start***********\n"); printf("**********2.exit************\n"); printf("****************************\n"); } void Guss_num(){ int num; int key = rand() % 100 + 1; while (1){ printf("請輸入數字\n"); scanf("%d", &num); if (num > key){ printf("猜大了\n"); } else if (num < key){ printf("猜小了\n"); } else{ printf("猜對啦~~\n"); break; } } } int main(){ int choose; do{ Menu(); scanf("%d", &choose); switch (choose) { case 1: Guss_num(); break; case 2: exit(0); break; default: printf("輸入錯誤,請重新輸入\n"); Menu(); break; } } while (choose); srand((unsigned)time(NULL)); system("pause"); return 0; }
2.寫程式碼可以在整型有序陣列中查詢想要的數字,
找到了返回下標,找不到返回-1.(折半查詢)
#include<stdio.h> #include<stdlib.h> #include<string.h> int main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 25, 47 }; int left = 0; int right = sizeof(arr) / sizeof(arr[1]) - 1; int mid = 0; int key = 9; while (left <= right){ mid = (left + right) / 2; if (arr[mid]>key){ --mid; right = mid; } else if (arr[mid] < key){ ++mid; left = mid; } else if (arr[mid] = key){ printf("find it!operator is %d ",mid); break; } else{ return -1; } } system("pause"); return 0; }
3.編寫程式碼模擬三次密碼輸入的場景。
最多能輸入三次密碼,密碼正確,提示“登入成功”,密碼錯誤,
可以重新輸入,最多輸入三次。三次均錯,則提示退出程式。
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> int main(){ int i = 0; char password[] = "123456"; char user[10]; for (i = 0; i < 3; i++){ printf("請輸入密碼:\n"); scanf("%s", &user); if (strcmp(password,user) == 0){ printf("密碼正確\n"); break; } else{ printf("輸入錯誤請重試!!\n"); } if (i == 3){ printf("exit!"); } } system("pause"); return 0; }
4.編寫一個程式,可以一直接收鍵盤字元,
如果是小寫字元就輸出對應的大寫字元,
如果接收的是大寫字元,就輸出對應的小寫字元,
如果是數字不輸出。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
void transverter();
int main(){
transverter();
system("pause");
return 0;
}
void transverter(){
char input = ' ';
printf("請輸入需轉換的字母\n");
while (1){
scanf("%c", &input);
if ((input > 64 && input<91)){
printf("%c的小寫字母是%c\n", input, (input + 32));
continue;
}
else if (input>96 && input < 123){
printf("%c的大寫字母是%c\n", input, (input - 32));
continue;
}
else if (input>47&&input<58)
{
continue;
}
else
{
continue;
}
}
return 0;
}