gpt4 book ai didi

c++ - 我怎样才能最好地环绕字母表的位置变化?

转载 作者:搜寻专家 更新时间:2023-10-31 02:06:48 24 4
gpt4 key购买 nike

我正在编写一个初学者程序,它首先输入一个整数 n,然后输入一个单词(全部大写),然后将每个字母在字母表中移动 n 个位置。我有向下移动的部分(见下面的代码),但我正在努力将它包裹起来,所以一旦它经过 Z,它就会从字母表的开头开始。有什么建议吗?

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main()
{
int n;
cin >> n;
string output = "";
string str;
cin >> str;
for (char c : str) {
c = c + n;
output = output + c;
}
cout << output << endl;

return 0;
}

最佳答案

可能是最容易理解的:

将输入的字符移动到[0,25]范围内

(c - A_idx)

添加偏移量

(c - A_idx) + n

获取偏移量的模数(环绕它)

(c - A_idx) + n) % Letters

将其映射回ascii期望的范围

((c - A_idx) + n) % Letters + A_idx

完整代码

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main()
{
int n;
cin >> n;
string output = "";
string str;
cin >> str;
const auto A_idx = 65;
const auto Z_idx = 90;
const auto Letters = Z_idx - A_idx + 1;// 26 maybe?
for (char c : str) {
c = ((c - A_idx) + n) % Letters + A_idx;
output = output + c;
}
cout << output << endl;

return 0;
}

关于c++ - 我怎样才能最好地环绕字母表的位置变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49715933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com