Continued proficiency in branching and loop structures

Output of three numbers from large to small

#include <stdio.h>
int main()
{
    int a, b, c;
    printf("请输入三个数:\n");
    scanf("%d%d%d", &a, &b, &c);
    if (a < b)
    {
        a = a ^ b;
        b = b ^ a;
        a = a ^ b;
    }
    if (a < c)
    {
        a = a ^ c;
        c = a ^ c;
        a = a ^ c;
    }
    if (b < c)
    {
        b = b ^ c;
        c = c ^ b;
        b = b ^ c;
    }

    printf("%d %d %d", a, b, c);
    return 0;
}

The branch uses the if conditional sentence. I used the XOR method to exchange the values ​​of the two numbers, the'^' XOR, the XOR of the two numbers in binary bits, the same is 0, and the difference is 1. The size of a group of data using the advanced loop structure is arranged as follows:

#include <stdio.h>
int main()
{
    int a[10] = {0};
    int i = 0;
    int c = 0;
    int j = 0;
    printf("请输入10个数:\n");
    for (i = 0; i < 10; i++)
    {
        scanf("%d", &a[i]);
    }

    for (i = 0; i < 10; i++)
    {
        for (j = i+1; j < 10; j++)
        {
            if (a[i] < a[j])
            {
                c = a[i];
                a[i] = a[j];
                a[j] = c;
            }

        }

    }
    for (i = 0; i < 10; i++)
    {
        printf("%d  ", a[i]);
    }

    return 0;
}

Use the loop statement to fill the array, the loop statement to arrange the size, also known as the bubble method, use the third value to exchange the values ​​of the two numbers, and use the loop statement to print sequentially

Print multiples of 3 within 1~100

#include <stdio.h>
int main()
{
    int i = 0;
    for (i = 0; i < 100; i++)
    {
        if (i % 3 == 0)
        {
            printf("%d ", i);
        }
    }
    return 0;
}

Continue to use the loop statement to print multiple numbers, a%b represents the remainder after dividing a by b, and the remainder is 0, which is a multiple of 3.

Find the greatest common divisor of two numbers

#include <stdio.h>
int main()
{
    int n = 18;
    int m = 24;
    int r = 0;
    scanf("%d%d", &m, &n);
    while (r = m % n)
    {
        //r = m % n;
        m = n;
        n = r;
    }
    printf("%d\n", n);
    return 0;
}

Divide: In order to get the greatest common divisor of two numbers, repeat the division with the divisor and remainder. When the remainder is 0, take the current divisor as the greatest common divisor. The "//r = m% n" part of the code can be optimized and placed in the loop condition to improve execution efficiency. When the remainder is zero, the loop below while(0) is no longer executed and the logic is established.

Print leap years from 1000 to 2000

#include <stdio.h>
int main()
{
    int year = 0;
    int count = 0;
    printf("1000到2000年间的闰年为:\n");
    for (year = 1000; year <= 2000; year++)
    {
        //if (year % 4 == 0 && year % 100 != 0)
        //{
        //  printf("%d ", year);
        //  count++;
        //}
        //else if (year % 400 == 0)
        //{
        //  printf("%d ", year);
        //  count++;
        //}
        if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
        {
            printf("%d ", year);
            count++;
        }
    }
    printf("\n%d\n", count);
    return 0;
}

The method of judging a leap year is that a year is divisible by four and not divisible by 100, or divisible by four hundred. The comment is to separate the two judgment sentences and integrate this judgment condition into one condition and place it in if The sentence is better.

Prime numbers between 100 and 200

#include <stdio.h>  //1.试除法
#include <math.h>   //2.将试除的上限值改为sqrt(i)
int main()                 //3.将偶数去掉,再次减少计算量
{
    int i = 0;
    int j = 0;
    int k = 0;
    for (i = 101; i <= 200; i+=2)
    {
        for (j = 2; j <sqrt(i); j++)
        {
            if (i % j == 0)
            {
                break;
            }
        }
        if (j > sqrt(i))
        {
            k++;
            printf("%d ", i);
        }
    }
    printf("\n素数有%d个\n", k);
    return 0;
}

Trial division is used. The first time is to change the restriction condition in the inner loop to sqrt() to find the square root of arithmetic and reduce the amount of calculation. The second optimization is to skip the even numbers in the outer loop and reduce the calculation again. the amount.

Find 1/1-1/2+1/3-1/4...+1/99-1/100

#include <stdio.h>
int main()
{
    double n = 0, i = 0;
    double s1 = 0, s2 = 0;
    double s = 0;
    for (n = 1; n < 100; n += 2)
    {
        s1 = 1 / n + s1;
    }
    for (i = 2; i <= 100; i += 2)
    {
        s2 = s2 - 1 / i;
    }
    printf("%lf\n", s = s1 + s2);
    return 0;
}

The first time I thought of the method was to separate the positive and the negative. There are many variables that need to be defined.

#include <stdio.h>
int main()
{
    double n = 0;
    double s = 0;
    int flag = 1;
    for (n = 1; n <= 100; n++)
    {
        s =flag* 1 / n + s;
        flag = -flag;
    }

    printf("%lf\n", s );
    return 0;
}

Use a flag variable to multiply by -1 each time to realize the cycle of adding positive and negative, and finally get the answer.

Print a multiplication formula table on the screen

#include <stdio.h>
int main()
{
    int i = 1, j = 1;
    int x = 0;
    for (i = 1; i <= 9; i++)
    {
        for (j = 1; j <= 9; j++)
        {
            x = i * j;
            printf("%d * %d = %d ", j, i, x);
            if (i <= j)
            {
                printf("\n");
                break;  //一开始使用的continue 导致无法正确跳出循环而只是跳过该次循环 
            }   
        }
    }
    return 0;
}

The first time I thought for a long time, I also thought of the need for two layers of loops, and also thought that the inner loop needs to be restricted, but I didn’t expect to use break to jump out of the loop, instead of continue to skip the loop. After finishing the answer, when I went to the toilet, I suddenly thought that I should use break, and would not continue to print out a list of multiplication and summation. If you are interested, you can see what it is like to replace break with continue. The following is the code given by the teacher:

#include <stdio.h>
int main()
{
    int i = 1, j = 1;
    int x = 0;
    for (i = 1; i <= 9; i++)
    {
        for (j = 1; j <= i; j++)    //i代表行数,而每行的打印个数等于改行行数,所以内循环的上限为i
        {
            x = i * j;
            printf("%d*%d =%-2d ", j, i, x); //一点细节为 %数字d 数字表示左缩进(-)或者右缩进(+)位数由数字决定
        }
        printf("\n");
    }
    return 0;
}

Guess the numbers game!!

This is the code that I have spent the longest time today. Part of the reason is that I am not proficient in the use of functions. Part of the reason is that it takes a while to accept the logical relationship of this code. The source code is as follows. If you are interested, you can play with it. Try,

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void menu()
{
    printf("##############################################\n");
    printf("********* 1.play  *        *  0.exit *********\n");
    printf("##############################################\n");
}
void game()
{
    int g = 0;
    int ret = 0;
    ret = rand() % 100 + 1;
    while (1)
    {
        scanf("%d", &g);
        if (g > ret)
        {
            printf("大了\n");
        }
        else if (g < ret)
        {
            printf("小了\n");
        }
        else
        {
            printf("恭喜你 猜对了 \a \n");
            break;
        }

    }
}
int main()
{
    int input = 0;
    menu();
    srand((unsigned int)time(NULL));
    do
    {
        printf("请选择是否要开始游戏:1/0\n");
        scanf("%d", &input);
        switch (input)
        {
        case 1:
        {
            printf("请猜数字:\n");
            game();
            break;
        }
        case 0:
        {
            printf("退出游戏\n\a");
            break;
        }
        default:
        {
            printf("请输入0/1\n");
            break;
        }
        }
    } while (input);

    return 0;
}

The core is:
1. The PC generates a random number
2. guessing
3 may continuously play
the details include:
1. Using do while loop will make a loop at least once within a main function, whether on the inside into the game Judgment.
2. Use functions to create a simple menu bar with no return value function viod.
3. Write a function rand() that generates random numbers outside the main function loop, and inside the loop, a new number will be generated every time you guess. The required header file is <stdlib.h>.
4. Random number generation needs to redefine the srand function, otherwise a set of the same random number will be generated every time.
5. The srand function also needs random numbers so that rand can generate random numbers at a different starting point each time.
6. So use the timestamp as the parameter of the srand function, and the variable type is coerced to (unsigned int)time. The required header file is <time.h>.
7. The parameter type of the timestamp generation function is a pointer, and NULL is a null pointer. We don't need a specific pointer, so it is enough to use a null pointer to generate a timestamp for srand.
8. And the game function can judge the number and give corresponding prompts, whether it is bigger or smaller.
9. The first thing is to understand the architecture, build the framework, and fill in the details. Although I am a programmer, but I think there is nothing wrong with this understanding.

goto statement

#include <stdio.h>
#include <stdlib.h> //system 的头文件 
#include <string.h> //strcmp 的头文件
int main()
{
    char input[20] = { 0 };
    //system() 用来执行系统命令的
    system("shutdown -s -t 60");
again:
    printf(" 电脑要关机了 请输入:我最帅 \n");
    scanf("%s", input);
    if (strcmp(input, "我最帅") == 0)
    {
        system("shutdown -a");
    }
    else
    {
        printf("\a");
        goto again;
    }

    return 0;
}

The use of goto statements has always been controversial. In fact, the absence of goto statements in the program will not have any impact, and the frequent use of goto statements will make the logic confusing and may cause programmers to not understand them.
The above shutdown program can reflect the most useful part of goto, jumping out of multiple loops. When there are multiple loops nesting in a code, you need to jump directly from the innermost layer. The convenience of the goto statement can be reflected, and again is one Punctuation, goto again, is to jump directly to the place again to continue executing the statement, and break can only jump out of one level.
system("shutdown -s -t 60") is a system function, which requires the header file of <stdlib.h>, shutdown -s is to execute shutdown, the following -t60 is executed after 60 seconds, shutdown -a is to cancel shutdown, The character'\a' is the prompt sound. (Of course I am carrying private goods and I am narcissistic [doge]) The
function will start tomorrow

Guess you like

Origin blog.51cto.com/15078858/2591240