仅用if else实现C++字母偏移加密(循环字母表+输入校验)
仅用if/else实现的C++单字母偏移加密程序
实现逻辑说明
- 优先做输入合法性校验:仅接受取值范围在(-26,26)且不为0的偏移量,不符合要求直接返回错误
- 区分大小写字母分别处理边界循环逻辑,全程仅用if/else做分支判断,不使用模运算或其他复杂语法
- 边界处理规则:
- 小写字母向右偏移超出
z时减26回到小写字母区间,向左偏移小于a时加26回到小写字母区间 - 大写字母向右偏移超出
Z时减26回到大写字母区间,向左偏移小于A时加26回到大写字母区间
- 小写字母向右偏移超出
完整可运行代码
#include <iostream> using namespace std; int main() { char inputChar, encryptedChar; int offset; cout << "请输入需要加密的单字母:"; cin >> inputChar; cout << "请输入偏移量(范围-25到25,且不为0):"; cin >> offset; // 偏移量合法性校验 if (offset >= 26 || offset <= -26 || offset == 0) { cout << "错误:偏移量无效" << endl; return 0; } int tempVal = inputChar + offset; // 小写字母加密逻辑 if (inputChar >= 'a' && inputChar <= 'z') { if (tempVal > 'z') { encryptedChar = tempVal - 26; } else if (tempVal < 'a') { encryptedChar = tempVal + 26; } else { encryptedChar = tempVal; } cout << "加密结果:" << encryptedChar << endl; } // 大写字母加密逻辑 else if (inputChar >= 'A' && inputChar <= 'Z') { if (tempVal > 'Z') { encryptedChar = tempVal - 26; } else if (tempVal < 'A') { encryptedChar = tempVal + 26; } else { encryptedChar = tempVal; } cout << "加密结果:" << encryptedChar << endl; } // 非字母输入处理 else { cout << "错误:输入内容不是合法字母" << endl; } return 0; }
测试用例参考
- 输入小写
z、偏移量+1,输出a - 输入大写
A、偏移量-1,输出Z - 输入小写
c、偏移量-3,输出z - 输入大写
Y、偏移量+3,输出B
内容的提问来源于stack exchange,提问作者Nahuel Scandroglio
相关产品推荐
相关产品推荐

