1. 不允许创建临时变量,交换两个数的内容

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int a = 10, b = 20;
    a = a + b;
    b = a - b;
    a = a - b;
    printf("a = %d b = %d\n", a, b);
    return 0;
}

2. 求10个整数中的最大值

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int arr[] = {2, 4, 1, 1, 7, 9, 3, 6, 5, 8};
    int max = arr[0];
    int i;
    for(i = 1; i < 10; i++) {
        if(arr[i] > max)
            max = arr[i];
    }
    printf("max = %d\n", max);
}

3. 将三个数按从大到小输出

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int i, j;
    int tmp;
    int arr[] = {2, 1, 3};

    for(i = 1; i <= 2; i++) {
        tmp = arr[i];
        for(j = i-1; j>=0 && arr[j]<tmp; j--) {
            arr[j+1] = arr[j];
        }
        arr[j+1] = tmp;
    }
    printf("%d %d %d\n", arr[0], arr[1], arr[2]);
}

4. 求两个数的最大公约数

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int i = 12, j = 8;
    int tmp = (i <= j) ? i : j;

    while(tmp >= 1) {
        if((i % tmp == 0) && (j % tmp == 0)) {
            printf("%d\n", tmp);
            break;
        }
        tmp--;
    }
}
Last modification:September 6th, 2019 at 07:46 pm