C learning_8

guess the number game

Guess the number game:

        1. The computer will randomly generate a number

        2. Guess the number

                a> guess too big, remind you guess too big, continue to guess

                b> Guess is too small, remind you to guess too small, continue to guess

                c> guessed right, congratulations, guessed right, the game is over

        3. You can continue to play after playing, do not want to exit the program

First of all, if we want to complete this game, we must generate a random number. Next, let's look at the function of generating random numbers.

 The rand() function generates a pseudo-random number , the parameter is void, and the return value is int type. When using it, you need to refer to the header file <stdlib.h>. Its function is to generate a random integer ranging between 0 and RAND_MAX. Where RAND_MAX is a constant, usually its value is 32767. Each time the rand() function is called, a new random number is returned. Next we use it to form three random functions.

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int i = 0;
    for(i=0;i<3;i++)
    {
        int randomNumber = rand();
        printf("%d\n", randomNumber);
    }
    return 0;
}

 I ran the program three times and found that the generated random numbers are the same, why?

At this point, we must pay attention to the bold font above - pseudo-random number

        The random number sequence generated by the rand function is a pseudo-random number sequence, not a real random number sequence, so the random number sequence generated each time is the same. This is because the rand function uses a pseudo-random number generation method called the linear congruential algorithm, which is generated based on the inherent characteristics of the computer (such as the clock cycle, the seed of the operating system, etc.), so each time the program is run The sequence of random numbers is the same.

        In order to avoid the generated random number sequence being the same every time, you can use the srand function to initialize the random number seed to change the generated random number sequence. Next, let's take a look at the srand function.

 The srand function sets a random starting point. The parameter is an unsigned integer (unsigned int), and there is no return value. When using it, you need to refer to the header file <stdlib.h>. The srand function is a random number seed in the C language standard library The initialization function is used to initialize the sequence of random numbers.

Its prototype is:

void srand(unsigned int seed);

Before using the rand function to generate random numbers, you need to call the srand function to set the random number seed to ensure that the random number sequence generated by each running program is different.

When we use the function srand to pass in 1, 2, and 3 respectively, different random numbers can be displayed

 But we want to generate random numbers that we can change by ourselves, instead of manually setting it to change, so we need to set a random seed, but we originally wanted to generate a random number, and now we need to generate a random seed, so this is not a contradiction Yet? In fact, we find that the time is changing every moment, so we can use the timestamp to set this random seed. This is the first thing we need to understand the concept of timestamp.

 timestamp

        Timestamp refers to the number corresponding to a specific time point, usually an integer. In computers, a timestamp usually refers to the number of seconds elapsed from a specific time (for example: January 1, 1970 0:00:00) to the current moment (called Unix timestamp), and it can also be Milliseconds, microseconds, and other time units. Timestamp is usually used to record and represent the time when an event occurs. It is not affected by time zone, so it has high precision and versatility. In programming, timestamps are often used to sort different events, calculate time differences, generate random number seeds, and other operations.

 So at this time we need to get the time of the computer, we need to use the time function.

         The time function is a function used to obtain the current system time in the C language standard library.

Its prototype is:

time_t time(time_t *tloc);

The time function returns the current system time and is represented by a value of type time_t (time_t is a data type used to represent time in the C language standard library). If the parameter is not NULL, the time function will also store the current time in the variable pointed to by the pointer. The time returned by the time function represents the number of seconds elapsed from January 1, 1970 0:00:00 to the current time, so it is also called a Unix timestamp. The time function can be used to obtain the current system time, calculate the time difference, determine the random number seed and other operations.

Pay attention to a small detail here. Since the parameter of the srand() function is (unsigned integer) unsigned int, the return value of the time function is time_t, so we need to cast the return value of the time function:

srand((unsigned int)time(NULL));

 At this time, we found that after using the timestamp as the random seed, the random numbers we generated were different.

In order to reduce the difficulty of the game, we want to generate a number between 1-100, we need to use the following method to generate it

rand()%100+1;

Next, let's look at the code of the complete guessing number game

//猜数字游戏
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
	printf("****************************\n");
	printf("******1.paly    0.exit******\n");
	printf("****************************\n");

}
void game()
{
	//1.生产随机数
	//srand((unsigned int)time(NULL));//要给srand传递一个变化的值,\
                                计算机上的时间是时刻发生变化的
	//srand( unsigned int seed )
	//time函数可以返回一个时间戳 - time_t
	//rand();//生产随机数,随机数范围0-32767
	int ret = rand() % 100 + 1;//生产随机数,随机数范围1-100
	//printf("%d", ret);
	//2.猜数字
	int guess = 0;
	while(1)
	{
		printf("请猜数字:>");
		scanf("%d", &guess);
		if (guess > ret)
		{
			printf("猜大了\n");
		}
		else if (guess < ret)
		{
			printf("猜小了\n");
		}
		else
		{
			printf("恭喜你,猜对了\n");
			break;
		}
	}
}
int main()
{
	int input = 0;
	srand((unsigned int)time(NULL));
	//打印菜单
	//1.玩游戏
	//2.退出游戏
	do
	{
		menu();
		printf("请选择:>");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			printf("猜数字游戏\n");
			game();
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("选择错误,请重新输入\n");
			break;
		}
	} while (input);
	
	return 0;
}

Friends who want to experience, you can try it yourself.

goto statement

        The C language provides goto statements that can be abused at will and labels that mark jumps, but they can only jump within the current function, and cannot jump across multiple functions.

        The goto statement is a jump statement that can be used to jump the execution of a program directly from one piece of code to a specific location in other code. It can be used anywhere in the program, but excessive use of goto statements can lead to code that is difficult to understand and maintain. When using the goto statement, you need to define a label to mark the target location of the jump. For example, if a piece of code needs to be executed multiple times, you can define a label at the beginning of the code block, and jump to the position of the label through the goto statement at the end of the code block, so as to realize the loop execution of the code block.

For example, here is a sample code that implements a loop using the goto statement:

#include <stdio.h>
int main()
{
    int i = 1;
LOOP:
    printf("%d ", i);
    i++;
    if (i <= 10)
        goto LOOP;
    return 0;
}

        In this sample code, we define a label LOOP, and use the goto statement to jump to the position of the label at the end of the code block. Every time the code block is executed, the program will execute the code in order until the condition of the if statement is met and jump to the position of the label LOOP, and then restart the execution of the code block, realizing the cyclic execution of the code block until the value of i up to 10.

        Excessive use of the goto statement may make the code difficult to understand and maintain, but the goto statement is still useful in some occasions. The most common usage is to terminate the processing of the program in some deeply nested structures. For example: Jump out of two or more layers of loops at a time. The use of break in this case of multi-layer loop cannot achieve the purpose. It can only exit from the innermost loop to the previous loop.

for (...)
for (...)
{     for (...)     {         if (disaster)             goto error;     } } error : if (disaster) // handle error cases








shutdown program

        1. When the program is running, it will shut down within one minute

        2. If 1 is entered, we will cancel the shutdown

        Here we first introduce a shutdown command: shutdown

         The Windows system comes with a program called Shutdown.exe , which can be used for shutdown operation (located under Windows\ System32 ). Generally, the shutdown of the Windows system can be  realized by calling the program shutdown.exe , and this program also Can be used to abort a planned shutdown.

//关机程序
// 1.程序运行起来,将会在一分钟内关机
// 2.如果输入1,我们就取消关机
#include<stdio.h>
#include<stdlib.h>
int main()
{
	int input = 0;
	//程序关机倒计时
again:
	system("shutdown -s -t 60");
	printf("请注意,你的电脑将在1分钟内关机,如果输入1,就会取消关机\n");
	scanf("%d", &input);
	if (input == 1)
	{
		system("shutdown -a");
	}
	else
	{
		goto again;
	}
	return 0;
}

system("shutdown -s -t 60");

        `system("shutdown -s -t 60")` is a call to the `system()` function, and its function is to execute a system command in the program that calls this function. In this particular example, the system command is `shutdown`, which is a command of the Windows operating system that can be used to shut down, restart, log off, and so on. The `-s` option means shutdown, `-t 60` means shutdown after 60 seconds. Therefore, this line of code means to shut down the computer that executes the program within 60 seconds after running the program.

system("shutdown -a");

        `system("shutdown -a")` is a `system()` function call, its function is to execute a system command in the program that calls this function. In this particular example, the system command is `shutdown`, which is a command of the Windows operating system that can be used to shut down, restart, log off, and so on. The `-a` option means to cancel the shutdown, restart and other commands that have been issued before. Therefore, this line of code means to let the computer that executes this program cancel the shutdown command that has been set before.

And if the goto statement is not applicable, you can use a loop:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int input[10] = 0;
    system("shutdown -s -t 60");
    while (1)
    {
        printf("电脑将在1分钟内关机,如果输入:1,就取消关机!\n请输入:>");
        scanf("%d", &input);
        if (1 == input)
        {
            system("shutdown -a");
            break;
        }
    }
    return 0;
}

The realm of n in the solution of prime numbers
 

Idea:
        prime number: a prime number, except for 1 and itself, there are no other divisors, then the data is a prime number, the specific method is as follows

//方法一:试除法
int main()
{
	int i = 0;
	int count = 0;


    // 外层循环用来获取100~200之间的所有数据,100肯定不是素数,因此i从101开始
	for(i=101; i<=200; i++)
	{
		//判断i是否为素数:用[2, i)之间的每个数据去被i除,只要有一个可以被整除,则不是素数
		int j = 0;
		for(j=2; j<i; j++)
		{
			if(i%j == 0)
			{
				break;
			}
		}
        
		// 上述循环结束之后,如果j和i相等,说明[2, i)之间的所有数据都不能被i整除,则i为素数
		if(j==i)
		{
			count++;
			printf("%d ", i);
		}
	}


	printf("\ncount = %d\n", count);
	return 0;
}


//上述方法的缺陷:超过i一半的数据,肯定不是i的倍数,上述进行了许多没有意义的运算,因此可以采用如下
// 方式进行优化
// 方法二:每拿到一个数据,只需要检测其:[2, i/2]区间内是否有元素可以被2i整除即可,可以说明i不是素数
int main()
{
	int i = 0;//
	int count = 0;


	for(i=101; i<=200; i++)
	{
		//判断i是否为素数
		//2->i-1
		int j = 0;
		for(j=2; j<=i/2; j++)
		{
			if(i%j == 0)
			{
				break;
			}
		}
		//...
		if(j>i/2)
		{
			count++;
			printf("%d ", i);
		}
	}


	printf("\ncount = %d\n", count);
	return 0;
}




/*
方法二还是包含了一些重复的数据,再优化:
如果i能够被[2, sqrt(i)]之间的任意数据整除,则i不是素数
原因:如果 m 能被 2 ~ m-1 之间任一整数整除,其二个因子必定有一个小于或等于sqrt(m),另一个大于或等于 sqrt(m)。
*/
int main()
{
	int i = 0;
	int count = 0;


	for(i=101; i<=200; i++)
	{
		//判断i是否为素数
		//2->i-1
		int j = 0;
		for(j=2; j<=sqrt(i); j++)
		{
			if(i%j == 0)
			{
				break;
			}
		}
		//...
		if(j>sqrt(i))
		{
			count++;
			printf("%d ", i);
		}
	}


	printf("\ncount = %d\n", count);
	return 0;
}


//方法4
/*
继续对方法三优化,只要i不被[2, sqrt(i)]之间的任何数据整除,则i是素数,但是实际在操作时i不用从101逐渐递增到200,因为出了2和3之外,不会有两个连续相邻的数据同时为素数
*/


int main()
{
	int i = 0;
	int count = 0;


	for(i=101; i<=200; i+=2)
	{
		//判断i是否为素数
		//2->i-1
		int j = 0;
		for(j=2; j<=sqrt(i); j++)
		{
			if(i%j == 0)
			{
				break;
			}
		}
		//...
		if(j>sqrt(i))
		{
			count++;
			printf("%d ", i);
		}
	}

	printf("\ncount = %d\n", count);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_64446981/article/details/130268241