No.16 代碼練習

學習不易,需要堅持。

1.寫代碼可以在整型有序數組中查找想要的數字,
找到了返回下標,找不到返回-1.(折半查找)

2.編寫代碼模擬三次密碼輸入的場景。
最多能輸入三次密碼,密碼正確,提示“登錄成功”,密碼錯誤,
可以重新輸入,最多輸入三次。三次均錯,則提示退出程序。

3.編寫一個程序,可以一直接收鍵盤字符,
如果是小寫字符就輸出對應的大寫字符,
如果接收的是大寫字符,就輸出對應的小寫字符,
如果是數字不輸出。

1.
//一個重要的查找算法:折半查找
//寫代碼可以在整型有序數組中查找想要的數字,找到了返回下標,找不到返回-1.(折半查找)

#include <stdio.h>

int Fold_half_search(int arr[], int sz, int key) 
{
	int left = 0 ;
	int right = sz - 1 ;
	int mid = 0 ; //中間值
	while(left <= right)
	{
		mid = ( left + right ) / 2 ;
		//查找成功
		if( key == arr[mid] ) 
		{
			return mid ;
		}
		//若查找失敗,則改變左右指針繼續查找
		if( arr[mid] < key )
		{
			left = mid + 1 ;
		}

		if( arr[mid] > key )
		{
			right = mid - 1 ;
		}
	}

	return -1 ;
}

void Print(int arr[], int sz)
{
	int i = 0 ;
	for(i=0; i<sz; i++)
	{
		printf("%d ", arr[i]) ;
	}

	printf("\n") ;
}


int main()
{
	int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9} ;
	int ret = 0 ;
	int input = 0 ;//需要查找的數
	int flag = 0 ; //標誌
	int size = sizeof(arr) / sizeof(arr[0]) ;
	printf("/******折半查找*****/\n") ;
	Print(arr, size) ;
	while( flag < 2 )
	{
		printf("請輸入你想要查找的數字: ") ;
		scanf("%d", &input) ;
		ret = Fold_half_search(arr, size, input) ;
		printf("下標爲:arr[%d]\n", ret) ;
		flag++ ;
	}
	return 0 ;
}

運行結果:
在這裏插入圖片描述

2.
//編寫代碼模擬三次密碼輸入的場景。
//最多能輸入三次密碼,密碼正確,提示“登錄成功”,密碼錯誤,可以重新輸入,最多輸入三次。三次均錯,則提示退出程序。

#include <stdio.h>
#include <string.h>

void Enter()
{
	int count = 0 ; //記錄輸入次數
	char name[] = "1016705287" ;
	char psw[] = "xagydx" ;
	char name_input[20] = { 0 } ;
	char psw_input[20] = { 0 } ;
	while ( count < 3 )
	{
		printf("請輸入QQ賬號: ") ;
		scanf("%s", name_input) ;
		printf("請輸入QQ密碼: ") ;
		scanf("%s", psw_input) ;

		if( ( strcmp(name, name_input) == 0 ) && (strcmp(psw, psw_input) == 0 ) )
		{
			printf("密碼輸入正確!\n") ;
			break ;
		}	

		else
		{
			printf("賬號或密碼輸入錯誤,請重新輸入!\n") ;
		}

		count ++ ;
	}
}

int main()
{
	Enter() ;
	return 0 ;
}

運行結果:
在這裏插入圖片描述

3.
//編寫一個程序,可以一直接收鍵盤字符,
//如果是小寫字符就輸出對應的大寫字符,
//如果接收的是大寫字符,就輸出對應的小寫字符,如果是數字不輸出。

#include <stdio.h>

char Judge(char ch) 
{
	//如果輸入的是小寫字母
	if( ch >= 97 && ch <= 122 ) 
	{
		printf("處理後的字符:%c", ch - 32) ;
	}
	//如果接收的是大寫字母
	if( ch >=65 && ch <= 90 )
	{
		printf("處理後的字符:%c", ch + 32) ;
	}
	//如果接收的是數字,則不輸出
	if( ch > 48 && ch <= 57 )
	{
		printf("檢測到數字\n") ;
		return ;
	}


}
int main()
{
    int count = 0 ;
	char ch = 0 ;
	while(count < 3)
	{
	printf("請輸入一個字符: ") ;
	scanf("%c", &ch) ;
	Judge(ch) ;  //判斷函數
	while ((ch = getchar()) != EOF && ch != '\n'); //清除緩衝區
	printf("\n") ;
	count++ ;
	}
	return 0 ;
}

運行結果:
在這裏插入圖片描述

學習不易,需要堅持。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章