1. 将数组A中的内容和数组B中的内容进行交换。(数组一样大)

#include <stdio.h>

void swap_arr(int* arr1, int size1, int* arr2, int size2) {
    int tmp = 0;

    for(int i = 0; i < size1; i++) {
        tmp = arr1[i];
        arr1[i] = arr2[i];
        arr2[i] = tmp;
    }
}

int main(int argc, char const *argv[])
{
    int arr1[] = {1, 3, 5, 7, 9};
    int arr2[] = {2, 4, 6, 8, 0};
    swap_arr(arr1, sizeof(arr1) / sizeof(int),
        arr2, sizeof(arr2) / sizeof(int));
    for(int i = 0; i < 5; i++)
        printf("arr1[%d] = %d arr2[%d] = %d\n", i, arr1[i], i, arr2[i]);

    return 0;   
}

2. 计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值。

#include <stdio.h>

int main(int argc, char const *argv[])
{
    double res = 0;
    int sign = 1;

    for(int i = 1; i <= 100; i++) {
        res += sign * (1.0 / i);
        sign *= -1;
    }
    printf("%lf\n", res);
    return 0;
}

3. 编写程序数一下 1到 100 的所有整数中出现多少次数字9。

#include <stdio.h>

int count9(int num) {
    int count = 0;
    while(num > 0) {
        if(num % 10 == 9)
            count++;
        num /= 10;
    }
    return count;
}

int main(int argc, char const *argv[])
{
    int count = 0;

    for(int i = 1; i <= 100; i++)
        count += count9(i);
    printf("%d\n", count);
    return 0;
}
Last modification:November 10th, 2019 at 10:22 am