所以我正在编写一个 C 程序来使用自定义表来使用凯撒算法,我将在其中给出该表并使用该表进行移位,例如文本“abc”根据表“abc”与 key= 1 应该被加密为 bca,但是如果字母的键+索引高于此处存储的表的长度是我的代码,那么我在最后一个字符上遇到困难
void encrypt (char table[],char entext[],char text[],int key)
{
int i,j;
int k = strlen(table);
//int result = (key + k);
for (i=0;i<strlen(table);++i)
{
j = 0;
if (text[i]!='\0')
{
while (text[i]!=table[j])
{
j++;
}
if ((j+key)>k)
{
j=(j+key)%k;
//j = (result - j);
}
else
j = j + key;
entext[i] = table[j];
}
}
entext[i+1] = '\0';
puts(entext);
}
int main()
{
char table[100] , text[100] , entext[100] , c;
int i , j , key;
printf("Enter the text : ");
gets(text);
printf("Enter the table : ");
gets(table);
printf("Enter the key : ");
scanf("%d",&key);
encrypt(table,entext,text,key);
system("pause");
return 0;
}
最佳答案
if ((j+key)>k)
应该是
if ((j+key)>=k)
此外,由于 mod 的工作原理,此检查完全没有必要。我将冒昧地重写您的代码,使其看起来更好:
void encrypt (char table[],char entext[],char text[],int key)
{
int i,j;
int k = strlen(table);
//int result = (key + k);
for (i=0;i<strlen(table);++i)
{
if (text[i]!='\0')
{
for(j=0; text[i] != table[j] ;j++);
entext[i] = table[(j+key)%k];
}
}
entext[i+1] = '\0';
puts(entext);
}
我相信你可以通过索引 char 本身的值来使这个“表”查找更有效,但是除非你正在处理相当大的输入,否则这不会真正产生影响。
关于凯撒密码算法移位 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22269827/