【问题标题】:What is wrong in this implementation of Caesar Cipher? [closed]这个凯撒密码的实现有什么问题? [关闭]
【发布时间】:2014-02-13 03:24:51
【问题描述】:

我正在尝试实现凯撒密码,但没有得到预期的输出。代码有什么问题?

Key: 3
Input: Hello
Output I'm getting: KNUUX    
Expected Output: KHOOR

代码:

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, string argv[])
{
    if(argc!=2)
    {
        return 1;
    }
    int k, i;
    k = atoi(argv[1]);
    printf("Enter the String to Encrypt: ");
    string s=GetString();
    for(i=0; i<strlen(s); i++)
    {
        if('A'>=s[i]<='Z')
        {
            s[i]=((s[i] - 'A' + k)%26) +'A';
        }
        else if('a'>=s[i]<='z')
        {
            s[i]=((s[i] - 'a' + k)%26) +'a';
        }
    }
    printf("The Encrypted Text is %s\n",s);        
}

【问题讨论】:

  • 使用isupper()islower()
  • 一些建议,因为您是初学者,(1) 编译的代码总是有帮助的,(2) typedef'ing 或 #define-ing char * as string 没有有帮助; 曾经.
  • @WhozCraig typedef 是哈佛在线的 CS50 头文件的一部分。这只是在课程的前两三周回避这个问题。对于这个有限的目的,它实际上是很有帮助的。

标签: c cs50 caesar-cipher


【解决方案1】:
if('A'>=s[i]<='Z')

确实没有按照您的预期行事。

你可能想要:

if ( (s[i] >= 'A') && (s[i] <= 'Z') )

【讨论】:

  • 我认为第一个表达式的比较是向后的。
  • @WhozCraig ...这就是我从无意义的代码中复制/粘贴的结果。谢谢。
  • 别担心,顺便说一句 +1。
【解决方案2】:
for(i=0; s[i]; ++i)
    if(isalpha(s[i]))
        s[i]=(toupper(s[i]) - 'A' + k)%26 +'A';

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 2014-03-27
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 2019-04-26
    • 1970-01-01
    相关资源
    最近更新 更多