C语言经典题目(PTA题)1

一.厘米换算成英尺英寸

​
#include <stdio.h>

int main() {
    int cm; 
    scanf("%d", &cm); // 输入厘米数

    // 将厘米数转换为米,再转换为英尺
    double total_feet = cm / 100.0 / 0.3048;  // 转换为英尺的小数形式

    // 计算英尺和英寸
    int feet = (int) total_feet;  // 取整数部分作为英尺数
    int inches = (int) ((total_feet - feet) * 12);  // 计算剩余的英寸并转换为整数

    // 输出英尺和英寸
    printf("%d %d\n", feet, inches);

    return 0;
}

​

 总结

  • 总英尺数:total_feet = cm / 100 / 0.3048
  • 取整数部分为英尺:feet = int(total_feet)
  • 计算剩余的部分,得到英寸数:inches =(int)(total_feet - feet) * 12

二.发奖金

#include <stdio.h>

int main() {
    int amount;
    scanf("%d", &amount);  // 读取奖金金额
    
    // 定义纸币面额,从大到小
    int denominations[] = {100, 50, 20, 10, 5, 2, 1};
    
    // 遍历每种纸币面额,计算对应的纸币张数
    for (int i = 0; i < 7; i++) {
        int count = amount / denominations[i];  // 当前面额的纸币张数
        amount = amount % denominations[i];     // 更新剩余金额
        
        // 输出纸币张数,格式化输出
        printf("%3d元: %2d张\n", denominations[i], count);
    }

    return 0;
}

总结

  • 我们通过预定义一个包含所有面额的数组 denominations[],使得代码具有更好的扩展性。如果以后需要新增面额,只需修改数组即可。

 三.旅游汽车

 

#include <stdio.h>

int main() {
    int n, b;
    scanf("%d %d", &n, &b);  // 输入职工人数和每辆车的容纳人数
    
    // 计算需要的最少车辆数
    int k = (n + b - 1) / b;  // 使用公式 (n + b - 1) // b 来向上取整
    
    printf("%d\n", k);  // 输出所需车辆数
    
    return 0;
}

  总结

  • n + b - 1 这部分是关键,通过这种方式,确保了如果有剩余的职工人数,就会向上取整计算需要的车辆数。

四.环形加密(简)

 

#include <stdio.h>
#include <stdlib.h> // 包含 abs 函数

// 环形加密函数
char circular_encrypt(char plaintext, int key) {
    // 获取密钥的绝对值并模 26,确保偏移量不超过字母表长度
    int shift = abs(key) % 26;

    // 顺时针加密 (key >= 0)
    if (key >= 0) {
        plaintext = (plaintext - 'a' + shift) % 26 + 'a';
    } 
    // 逆时针加密 (key < 0)
    else {
        plaintext = (plaintext - 'a' - shift + 26) % 26 + 'a';
    }

    return plaintext;
}

int main() {
    char plaintext;
    int key;
    
    // 读取明文和密钥
    scanf("%c %d", &plaintext, &key);
    
    // 输出加密后的密文
    printf("%c\n", circular_encrypt(plaintext, key));
    
    return 0;
}

总结

关键步骤:

// 顺时针加密 (key >= 0)
    if (key >= 0) {
        plaintext = (plaintext - 'a' + shift) % 26 + 'a';
    } 
// 逆时针加密 (key < 0)
    else {
        plaintext = (plaintext - 'a' - shift + 26) % 26 + 'a';
    }

深度解析: 

这两步代码实现了环形加密的核心部分。下面我们将对每一行代码进行深度解析,详细分析它们如何实现顺时针和逆时针的字母加密。

目标:

我们要根据给定的密钥 (key) 对字母进行加密。字母表是环形的,因此,当加密过程中的位置越界时,需要从字母表的另一端继续。加密方向是根据密钥的符号决定的:

  • 如果密钥是正数 (key >= 0),我们进行顺时针加密。
  • 如果密钥是负数 (key < 0),我们进行逆时针加密。

顺时针加密(当 key >= 0 时):

plaintext = (plaintext - 'a' + shift) % 26 + 'a';

1. plaintext - 'a'

  • plaintext 是输入的明文字母。
  • 'a' 是字符 'a' 的 ASCII 码,约为 97。
  • plaintext - 'a' 将字母转换为它在字母表中的位置(从 0 到 25)。
    例如:
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值