参考程序1:
#include <iostream>
#include <string>
using namespace std;
int main() {
string cipher;
int n;
// 因为题目说明密文只包含大小写字母(没有空格),所以用 >> 读就可以了
cin >> cipher;
cin >> n;
n = n % 26; // 因为字母表只有26个字母,大的移位数可以取模
string lower = "abcdefghijklmnopqrstuvwxyz";
string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string result = "";
for (char ch : cipher) {
if (isupper(ch)) { // isupper(ch) 判断 ch 是否是大写字母(A–Z)。
// 找到 ch 在大写字母环里的位置(0..25)
int pos = (int)upper.find(ch);
// 解密:向右移动 n 位(+n),再对26取模(环形)
int newPos = (pos + n) % 26;
result += upper[newPos];
} else if (islower(ch)) { //islower(ch) 判断 ch 是否是小写字母(a–z)。
int pos = (int)lower.find(ch);
int newPos = (pos + n) % 26;
result += lower[newPos];
} else {
// 题目说只有字母,这里只是保守处理:非字母直接原样加
result += ch;
}
}
cout << result << '\n';
return 0;
}
参考程序2:
#include <iostream>
#include <string>
using namespace std;
int main() {
string cipher;
int n;
cin >> cipher;
cin >> n;
n = n % 26; // 把大于26的移位数变成 0..25 之间
string result = "";
for (char ch : cipher) {
if (isupper(ch)) {
char base = 'A'; // 'A' 对应索引 0
int index = ch - base; // 当前字母是第几(0..25)
int newIndex = (index + n) % 26; // 向右移动 n 位,再取模
result += char(base + newIndex); // 还原成字符加入结果
} else if (islower(ch)) {
char base = 'a'; // 'a' 对应索引 0
int index = ch - base;
int newIndex = (index + n) % 26;
result += char(base + newIndex);
} else {
result += ch; // 不是字母的话,直接加上(题目里不会有,但这样更稳妥)
}
}
cout << result << '\n';
return 0;
}
参考程序3:
#include <iostream>
#include <string>
using namespace std;
int main() {
string cipher; // 保存密文
int n; // 移动位数
cin >> cipher; // 输入密文
cin >> n; // 输入移位数
n = n % 26; // 字母只有26个,取模避免多余的循环
string result = ""; // 保存解密结果
for (char ch : cipher) {
if (ch >= 'A' && ch <= 'Z') {
// 大写字母的情况
char base = 'A'; // 'A'当作起点(索引0)
int index = ch - base; // 算出当前字母在字母表的位置(0..25)
int newIndex = (index + n) % 26; // 向右移动n位
result += char(base + newIndex); // 算出新字母,加到结果里
} else if (ch >= 'a' && ch <= 'z') {
// 小写字母的情况
char base = 'a';
int index = ch - base;
int newIndex = (index + n) % 26;
result += char(base + newIndex);
} else {
// 如果不是字母(虽然题目保证不会有),就原样加进去
result += ch;
}
}
cout << result << '\n'; // 输出解密后的原文
return 0;
}