因此,我完成了一个程序,该程序以Julius Ceasar的方式对输入进行加密(向所有字母添加一个常数)。
在到达z + 6障碍之前,该程序似乎运行良好,此时它开始消除将使字母变为圆形的if语句。
我只是不明白为什么当它到达那个点时它将停止工作。
这是我的代码:
#include <iostream>
using namespace std;
char encoded(char c, int k) {
k %= 26; //too big numbers!
c += k; //encrypt
if (c > 'z')
c = c-'z'+ 'a' -1; //circular alphabet
c = c - 'a' +'A'; //uppercase
return c;
}
int main () {
int k;
while (cin >> k) {
char c;
while (cin >> c and c != '.') {
if ('a' <= c and c <= 'z')
cout << encoded(c,k);
else if (c == '_')
cout << ' ';
else
cout << c;
}
cout << endl;
}
}
如果有人可以告诉我发生了什么事,我将不胜感激。
代码中的问题是溢出。数据类型的char
范围可能从-128到127(取决于体系结构)。``z''的ASCII码是122,所以122 + 6不是128,而是-128。
您可以解决它:
char encoded(char c, int k) {
const int len = 'z'+1-'a';
int ch = (int)c + k%len; //encrypt
if (ch > 'z')
ch = ch - len; //circular alphabet
ch = ch - 'a' +'A'; //uppercase
return (char)ch;
}
我更喜欢这种解决方案:将您的字符转换为从0到小于26的数字进行编码,然后将其转换回字符。
char encoded(char c, int k) {
const int len = 'z'+1-'a';
if ( c >= 'a' && c <= 'z' )
c = (c-'a' + k) % len + 'A'; // + 'A' because of toupper ( +'a' keep lower)
return c;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句