【发布时间】:2016-04-27 17:42:16
【问题描述】:
我正在将此代码用于 Caesar 的密码加密程序。 c = (alpha + k) % 26; //c = 密文 ASCII 码,“alpha”字母 ASCII 码,“k”密钥为密文;这个等式在所有 26 个字母上给了我零 (0)。
谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main (int argc, string argv[]) {
// took key from user and converted it to int
int k = atoi (argv[1]);
// get plaintext from user
string p = GetString ();
int c = 0, alpha = 0;
for (int i = 0, n = strlen(p); i < n; i++)
{
// if it is alphabet else if not alphabet
if (isalpha (p[i]) == true) {
// if it is capital case else lower case
if (isupper(p[i]) == true) {
alpha = p[i] - 65;
// add key to plaintext then take modulas
c = (alpha + k) % 26;
alpha = c + 65;
} else {
alpha = p[i] - 97;
// add key to plaintext then take modulas
c = (alpha + k) % 26;
alpha = c + 97;
}
} else {
alpha = p[i];
}
printf("%c \n", alpha);
}
}
【问题讨论】:
-
您使用的是 C 还是 C++。你说 C 但你标记为 C++。
-
你试过调试了吗?
-
与您的问题无关,但请尽量避免magic numbers,例如
65。请改用'A'等正确的字符文字。 -
有趣,以前从未见过
int main (int argc, string argv[])。 -
代码不完整。可能没有人,但你的班级有 cs50.h。没有它,您的代码将无法编译。
标签: c encryption cs50 caesar-cipher