- 猜数字游戏
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int menu() {
int c;
do {
printf("--------------------\n");
printf("-------1.play-------\n");
printf("-------2.exit-------\n");
printf("--------------------\n");
scanf("%d", &c);
if (c == 2) {
break;
}
if (c != 1) {
printf("error! plese enter number 1 or 2\n");
}
} while (c != 1);
return c;
}
int game() {
srand((unsigned int )time(0));
int answer = rand() % 100 + 1;
int a,flag=1;
while(flag == 1) {
printf("plese enter a number:");
scanf("%d", &a);
if (a > answer) {
printf("The answer is smaller\n");
}
else if (a < answer) {
printf("The answer is bigger\n");
}
else {
printf("congratulation!!!You are so good!!!\n");
flag = 0;
}
}
return 0;
}
int main() {
if (menu() == 2) {
return 0;
}
else {
game();
}
system("pause");
return 0;
}
这个游戏还可以吧,不是特别难,但是坑有点多,调试了好一会。
2. 写代码可以在整型有序数组中查找想要的数字,找到了返回下标,找不到返回-1.(折半查找)。
#include <stdio.h>
#include <stdlib.h>
int search(int a[],int left,int right,int find){
int mid;
while(left<=right){
mid=(right-left)/ 2;
if(a[mid]>find){
right=mid-1;
}
else if(a[mid]<find){
left=mid+1;
}
else if(a[mid]==find){
return mid;
}
else{
return -1;
}
}
}
int main(){
int a[10]={1,4,6,8,12,23,34,45,56,78};
int find,i;
int left=0;
int right=9;
scanf ("%d",&find);
i=search(a,left,right,find);
printf("%d",i);
system("pause");
return 0;
}
这段代码有点问题,我稍后再调试一下。
- 编写代码模拟三次密码输入的场景。最多能输入三次密码,密码正确,提示“登录成功”,密码错误,可以重新输入,最多输入三次。三次均错,则提示退出程序。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int password(){
int i;
char key1[12];
char key[]="kishereisgod";
for(i=0;i<3;i++){
printf("palese enter the password:");
scanf("%s",key1);
if(0==strcmp(key,key1)){
//字符串不要取地址
//判断字符串是否相等不能用等号比较
break;
}else {
printf("worng password!\n");
}
}
return i;
}
int main(){
int i=password();
if(i==3){
printf("you have entered the wrong password for three times,push any key to exit.");
}else if(i<3){
printf("welcome my friends!");
}
system("pause");
return 0;
}
注释的那两个地方深坑。
- 编写一个程序,可以一直接收键盘字符, 如果是小写字符就输出对应的大写字符, 如果接收的是大写字符,就输出对应的小写字符, 如果是数字不输出。
#include<stdio.h>
#include<stdlib.h>
int main (){
long long cha;
printf("please enter the characters:");
while ((cha = getchar()) != EOF) {
if (cha>='a'&&cha<='z'){
printf("\n%s ", cha - 32);
}
else if (cha >= 'A'&&cha <= 'Z') {
printf("\n%s", cha + 32);
}
}
system("pause");
return 0;
}