其他分享
首页 > 其他分享> > 【PAT乙级】1101 B是A的多少倍 (15 分) C语言实现

【PAT乙级】1101 B是A的多少倍 (15 分) C语言实现

作者:互联网

题目:

1101 B是A的多少倍

代码实现:

  1. 解法一
#include <stdio.h>
#include <string.h>

int main() {
    char arr[11];
    int d;
    if (scanf("%s %d", arr, &d) == 2) {
        // 数组的长度
        int len = strlen(arr);

        // 将 arr 转为整数 a
        int a = 0;
        for (int i = 0; i < len; i++) {
            a = a * 10 + (arr[i] - '0');
        }

        // 根据给定的数目,翻转数组
        char target[11];
        int j = 0;
        for (int i = len - d; i < len; i++) {
            target[j++] = arr[i];
            arr[i] = '\0';
        }
        target[j] = '\0';

        // 连接两个数组,组成目标数组
        strcat(target, arr);

        // 将 target 转为整数 b
        int b = 0;
        for (int i = 0; i < len; i++) {
            b = b * 10 + (target[i] - '0');
        }

        double f = (double) b / a;
        printf("%.2f\n", f);
    }

    return 0;
}

/*
    字符串转整数:
    使用 stdlib.h 库中的 atoi 函数:
    C 库函数 int atoi(const char *str) 把参数 str 所指向的字符串转换为一个整数(类型为 int 型)。

    // 将 arr 转为整数 a
    int a = atoi(arr);
*/
  1. 解法二
#include <stdio.h>

int main() {
    int a, d;
    if (scanf("%d %d", &a, &d) == 2) {
        // 获取 a 里面中 d 位的数
        int n = 1;
        for (int i = 0; i < d; i++) {
            n = n * 10;
        }
        int b = a % n;
        int a1 = a / n;

        // 生成新的数 b
        int t = a1;
        while (t != 0) {
            t = t / 10;
            b = b * 10;
        }
        b = b + a1;

        // double f = (double) b / a;
        double f = b * 1.0 / a;
        printf("%.2f\n", f);
    }

    return 0;
}

标签:10,arr,15,target,int,double,len,C语言,1101
来源: https://www.cnblogs.com/wanghuizhao/p/16312229.html