当前位置:网站首页>【C】 Guess the number, shut down the applet, and practice some branch loops
【C】 Guess the number, shut down the applet, and practice some branch loops
2022-04-22 03:24:00 【Xin Xiangrong】
Blog home page : Xin Xiangrong
Series column :【 from 0 To 1,C Language learning 】
A short sentence : If you are in full bloom , Butterflies come !
Blog description : Do what you can , Write every blog , Help yourself familiarize yourself with what you have learned , I also hope these contents can help some partners on the way of learning , If errors and deficiencies are found in the article , Also hope to leave a message in the comment area , We communicate progress together !
Preface
Sum up, analyze and realize the number guessing game , Shutdown Sequence , There are also some exercises for learning branches and cycles , Contains a simple and error prone written test question .
Catalog
1️⃣ Realize the number guessing game
2️⃣ Shut down the applet
3️⃣ Branch and loop exercises
.1 Guess the number game
Fulfill the requirements : First print a menu on the screen , Generate a 1 To 100 Play a number guessing game with random numbers , Guess big or guess small , Until you're right ; To realize the game, you can play it all the time , Unless you don't want to play and choose to quit .
Setting a random number requires rand This function , Using this function requires a reference to the header file <stdlib.h>
rand The return value of the function is 0 To RAND_MAX Pseudo random integers in the range , Calling rand Before , Use srand Function to seed the pseudo-random number generator .

That is to say, they are using rand Function before , Need to use srand Set a random starting point ,rand To generate a real random number .
srand An unsigned integer argument is required , But if you just set a fixed integer , The random number generated by the first program execution is the same as that of running the program again after the first program execution , therefore srand The parameters here need to be variable , Here we will introduce the concept of timestamp ,

Use time function , Pay attention to the header file <time.h>, You can use the cast operator to change time() The return type of , The argument in this function is a pointer , If you don't want to use it, you can assign a null pointer to it srand((unsigned int)time(NULL));srand Function only needs to be set once to set the starting point in the program , Cannot be set more than once .
#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()
{
// First get a random number
int a = 0;
int ret = rand() % 100 + 1;
while (1)// Cycle until you guess right, and the cycle ends
{
printf(" Enter the number you guessed :>");
scanf("%d", &a);// Enter the guessed number
if (a > ret)
{
printf(" Guess the \n");
}
else if (a < ret)
{
printf(" Guess a little \n");
}
else
{
printf(" It's too awesome , Guessed it \n");
break;
}
}
}
int main()
{
int input = 0;
srand((unsigned int)time(NULL));// You can't put it in game In a function or loop , Can only be set once
do
{
menu();// First print a menu to provide options
printf(" Please select :>");
scanf("%d", &input);// Input selection
switch (input)
{
case 1:
game();// The process of guessing numbers
case 0:
break;
default:
printf(" Input error , Please re-enter \n");
}
} while (input);
printf(" Game over \n");
return 0;
}

.2 Shut down the applet
strcmp Function to compare whether two strings are equal , Need a lead file <string.h>
system Function is used to execute system commands , Need a lead file <windows.h>
shutdown -s -t 60 Indicates setting the countdown 60 Shutdown in seconds
shutdown -a Indicates that the shutdown is cancelled
#include<stdio.h>
#include<windows.h>
#include<string.h>
int main()
{
char input[30] = {
0 };
system("shutdown -s -t 120");
while (1)
{
printf(" Please note that , Your computer will be in 120 Power off in seconds , Enter that I am a big baby to cancel the shutdown \n");
scanf("%s", input);
if (strcmp(input, " I'm a big baby ") == 0)
{
system("shutdown -a");
break;
}
}
return 0;
}
The part of canceling shutdown can be designed by ourselves , Can make this applet more interesting , For example, the part of canceling shutdown can be combined with the number guessing game above .
The code is as follows :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include<windows.h>
#include<string.h>
void menu()
{
printf("######################\n");
printf("########1.play########\n");
printf("########0.exit########\n");
printf("######################\n");
}
int game()
{
// First get a random number
int a = 0;
int ret = rand() % 100 + 1;
while (1)
{
printf(" Enter the number you guessed :>");
scanf("%d", &a);
if (a > ret)
{
printf(" Guess the \n");
}
else if (a < ret)
{
printf(" Guess a little \n");
}
else
{
printf(" It's too awesome , Guessed it \n");
return 1;
}
}
}
int main()
{
system("shutdown -s -t 120");
printf(" Please note that , The game begins. Your computer will be in 120 Power off in seconds ,\n");
printf(" Play a number guessing game , Guess right and cancel the shutdown \n");
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();// First print a menu to provide options
printf(" Please select :>");
scanf("%d", &input);
switch (input)
{
case 1:
if(game());// Realize the process of guessing numbers. If you guess right, return 1
{
system("shutdown -a");
}
case 0:
break;
default:
printf(" Input error , Please re-enter \n");
}
} while (input);
return 0;
}
You can put the code in Release Run in the environment to generate an executive program (exe file ), Put this exe Documents can be sent to friends for entertainment , Of course, be careful not to play too much !
Generate exe The procedure of the document is as follows :

Then we can find one in the file directory where our project is located exe file , You can make a copy of this file and change its name .

.3 Practice hand exercises
1. A written test question , See how many times it has to cycle
#include <stdio.h>
int main()
{
int i = 0;
int k = 0;
for(i =0,k=0; k=0; i++,k++)
k++;
return 0;
}
It's easy to get wrong : The judgment part is k = 0, instead of k == 0; So the judgment part is false , Not once .
2. Calculation n The factorial .
#include<stdio.h>
int main()
{
int n = 0, i = 0,sum = 1;
printf(" Who calculates the factorial :>");
scanf("%d",&n);
for (i = 1; i <= n; i++)
{
sum *= i;
}
printf("n The factorial of is :>%d\n",sum);
return 0;
}
3. Calculation 1!+2!+3!+……+n!
#include<stdio.h>
// seek 1 To n Factorial and comparison of the two methods
// The two methods are different in simplicity
int main()// Method 1 is better
{
int ret = 1, sum = 0, i = 0,n = 0;
scanf("%d",&n);
for (i = 1; i <= n; i++)
{
ret *= i;
sum += ret;
}
printf("%d\n",sum);
return 0;
}
int main()// Method 2
{
int ret = 1, sum = 0, i = 0,j = 0,n = 0;
scanf("%d",&n);
for (i = 1; i <= n; i++)
{
ret = 1;
for (j = 1; j <= i; j++)
{
ret *= j;
}
sum += ret;
}
printf("%d\n", sum);
return 0;
}
4. Write code , Demonstrate the movement of multiple characters from both ends , Converging in the middle .
#include <stdio.h>
#include<windows.h>
int main()
{
char arr1[] = {
"My name is mrr" };
char arr2[] = {
"##############" };
int left = 0, reight = strlen(arr1)-1;
Method 1 : Use while Cycle to achieve
//while (left <= reight)
//{
// arr2[left] = arr1[left];
// arr2[reight] = arr1[reight];
// left++;
// reight--;
// printf("%s\n",arr2);
// Sleep(1000);
// system("cls");
//}
// Method 2 : Use for Cycle to achieve
for (left = 0,reight = strlen(arr1)-1;left <= reight ;left++,reight--)
{
arr2[left] = arr1[left];
arr2[reight] = arr1[reight];
printf("%s\n", arr2);
Sleep(1000);// Sleep 1 second
system("cls");// Clear the screen
} // Pause after each character replacement 1 second , And then empty , Display the next replacement
printf("%s\n", arr2);
return 0;
}
5. Write code to achieve , Simulate user login scenarios , And can only log in three times .
Only three passwords are allowed , If the password is correct, you will be prompted to log in as , If all three inputs are wrong , Then exit the program .
#include<stdio.h>
int main()
{
char psw[10] = {
"" };
int i = 0;
for (i = 1; i <= 3; i++)
{
printf(" Please input a password :>");
scanf("%s",psw);
if (strcmp(psw,"pasworld") == 0)
{
break;
}
}
if (i == 4)
{
printf(" Three input errors , Log out ");
}
else
{
printf(" Login successful ");
}
return 0;
}
Conclusion
Dear friends , It's fate to see here , I hope my content can bring you a little help , If you can, support it for three times ( Focus on ️ give the thumbs-up ️ Comment on ️)!!!
Thank you for coming here , We can learn and communicate together , Progress together !!! come on. !!!

版权声明
本文为[Xin Xiangrong]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220321300800.html
边栏推荐
- Rasa对话机器人连载一 第121课:Rasa对话机器人Debugging项目实战之电商零售对话机器人运行流程调试全程演示-1
- The mountain is high and the road is far away, fearing no danger
- Jiarong Technology Shenzhen Stock Exchange listed and discovered: The Value of Market of the company is 4.1 billion, and the Accounts receivables are 280 million.
- Nacos access message 404
- Application packaging or test team?
- Polyfill是什么?
- Ali II: can the main method be inherited?
- JS 数字千位分隔符且保留两位小数
- Single example of multithreading
- TP5 is making QR code
猜你喜欢

Nacos access message 404

Programmers want to take root in Shenzhen. In addition to Tencent, they can also consider these companies

List of persons elected to IEEE fellow in 2022

嘉戎技术深交所上市破发:公司市值41亿 应收账款2.8亿

吉他樂理整理

【云计算】3台虚拟机完成Spark Yarn集群部署并编写Scala应用程序实现单词计数统计

Error report: modulenotfounderror: no module named 'Astra‘

GPU deep learning environment configuration

Go language -----30-----token mechanism, WeChat official account signature verification method, XML parsing, CDATA parsing, exchange protocol, receive message protocol, passive reply message protocol,

C language to achieve three chess
随机推荐
Vos3000 8.05 installation and source code
The wangeditor rich text editor uses and converts the content of the editor to JSON format
leetcode:297. 二叉树的序列化与反序列化
H5 performance analysis is coming~
Saas. Extended field custom field
Technology sharing | selenium test case writing
TP5使用phpoffice/phpexcel包操作excel(导出)
职场礼仪.怎么写邮件
Oracle 11g enterprise installation tutorial
Computer wechat built-in browser turns on debugging mode
Analysis of five data structures of redis
Manual lock implementation of multithreading
Database management tools
Leetcode dictionary order
Application packaging or test team?
Summarize the differences between queue: work and queue: listen
Sword finger offer special breakthrough version 93, longest Fibonacci series
GPU deep learning environment configuration
Database Basics
ONEFLOW's global tensor study notes and internship summary


