0
点赞
收藏
分享

微信扫一扫

C语言基础编程题(整数算法训练)

未定义变量 2022-02-03 阅读 45

文章目录


在这里插入图片描述

1.通过编程实现,统计1~n有多少个9

#include <stdio.h>

int single_count(int x);
int multiple_count(int n);

int main() {
    printf("total %d '9'\n", multiple_count(100));

    return 0;
}

int single_count(int x) {
    int count = 0;

    while (x) {
        if(x % 10 == 9)
            count++;
        x /= 10;
    }

    return count;
}

int multiple_count(int n) {
    int count = 0;

    for (int i = 1; i <= n; i++)
        count += single_count(i);

    return count;
}

2.n个人围成一圈,顺序排号,从第一个人开始从1到3循环报数,报到3的人退出,求最后最后留下的是原来的几号

#include <stdio.h>

#define MAX_SIZE 100

int last_one(int *num ,int n);

int main() {
    int num[MAX_SIZE] = {0};
    int n = 5, i;

    for (i = 0; i < n; i++)
        num[i] = i;

    printf("%d\n", last_one(num, n));

    return 0;
}

int last_one(int *num ,int n) {
    int i = 0, count;
    int sum = n;//remaining quantity

    while (sum > 1) {
        count = 2;
        /*continue to find two from the current position*/
        while (count) {
            while (num[(i + 1) % n] == -1)
                i = (i + 1) % n;
            i = (i + 1) % n;

            count--;
        }
        num[i] = -1;//eliminate
        sum--;

        while (num[(i + 1) % n] == -1)
            i = (i + 1) % n;
        i = (i + 1) % n;
    }

    return i;
}

3.通过终端命令输入5个数(含负数、小数),将它们按由小到大的顺序排列起来

要求需要排序的数字通过参数传递.
例如:输入./code.out -1 2.1 -3 5 7,输出-3 -1 2.1 5 7

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

int main(int argc, char *argv[], char *env[]) {
    double num[MAX_SIZE] = {0};
    int i, j;
    int len = argc - 1;

    /*initialization*/
    for (i = 0; i < len; i++)
        num[i] = atof(argv[i+1]);

    /*output*/
    for (i = 0; i < len; i++)
        printf("num[%d]:%10lf%c", i, num[i], (i == len-1) ? 10 : 32);

    /*bubble sort*/
    for (i = 0; i < len; i++) {
        for (j = 0; j < len-i-1; j++) {
            if (num[j] > num[j+1]) {
                num[j] = num[j] + num[j+1];
                num[j+1] = num[j] - num[j+1];
                num[j] = num[j] - num[j+1];
            }
        }
    }

    /*output*/
    for (i = 0; i < len; i++)
        printf("num[%d]:%10lf%c", i, num[i], (i == len-1) ? 10 : 32);

    return 0;
}

在这里插入图片描述

4.求100以内的素数,全部打印出来

#include <stdio.h>

int is_prime(int n) {
    for (int i = 2; i < n; i++) {
        if (n % i == 0)
            return 0;
    }

    return 1;
}

int main() {
    for (int i = 2; i <= 100; i++) {
        if (is_prime(i))
            printf("%d ", i);
    }

    return 0;
}

5.请找出1000以内的所有完数

一个数如果恰好等于它的因子之和,这个数被称为完数(6 = 1+2+3)。

#include <stdio.h>

int is_perfect(int n) {
    int count = 0;

    for (int i = 1; i < n; i++) {
        if (n % i == 0)
            count += i;
    }

    return (count == n) ? 1 : 0;
}

int main() {
    for (int i = 6; i < 1000; i++) {
        if (is_perfect(i))
            printf("%d ", i);
    }

    return 0;
}
举报

相关推荐

0 条评论