折半查找 判断左右
#include<stdio.h>
#include<stdlib.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)
{
right = mid - 1;
}
else if (arr[mid]<key)
{
left = mid + 1;
}
else
break;
}
if (left <= right){
printf("找到了,下标是%d\n", mid);
}
else{
printf("找不到\n");
}
system("pause");
}
2.猜数字 注意time函数的引用头文件.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
printf("=============================\n");
printf("1.开始游戏\n");
printf("0.退出游戏\n");
printf("=============================\n");
}
void game()
{
int ret_num = rand() % 100 + 1;
int num = 0;
while(1){
printf("请输入猜的数字:");
scanf("%d", &num);
if (num > ret_num){
printf("高了!\n");
}
else if (num < ret_num){
printf("低了!\n");
}
else{
printf("恭喜你猜对了!\n");
break;
}
}
}
int main1()
{
int num = 0;
srand((unsigned)time(NULL));
menu();
printf("请做出你的选择\n");
scanf("%d", &num);
switch (num){
case 1:game();
break;
case 0:printf("good bye!\n");
break;
case 3:
printf("您的输入有错误!\n");
break;
}
system("pause");
}
3.登陆程序 三次出错则退出。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char arr[10] = {0};
int i = 0;
char *a = "123456";
for (i = 0; i < 3; i++){
printf("请输入密码:\n");
scanf("%s", arr);
if (strcmp(arr, a) == 0){
printf("密码正确!\n");
break;
}
else{
printf("密码错误,请重新输入!\n");
}
}
if (i == 3)
{
printf("连续输入三次错误,goodbye!\n");
}
system("pause");
return 0;
}
4.字符转换依靠Ascii码进行转换±32 比较大小。
#include<stdio.h>
#include<stdlib.h>
int main(){
int ch = 0;
printf("输入一个字符!\n");
while ((ch = getchar()) != 0){
if (ch >= 'a'&&ch <= 'z'){
printf("%c", ch - 32);
}
if (ch >= 'A' && ch <= 'Z'){
printf("%c", ch + 32);
}
if (ch >= '0'&&ch <= '9'){
printf("\n");
}
}
system("pause");
return 0;
}