代码之家  ›  专栏  ›  技术社区  ›  Shaun

CS50 PSET 2 Caesar错误结果

  •  -2
  • Shaun  · 技术社区  · 7 年前

    使用23作为密钥将“barfoo”加密为“yxocll” 输出无效的ASCII文本 日志 正在运行/凯撒23。。。 正在检查输出“密文:yxocll”。。。

    有人看到我的代码有什么问题吗?它似乎对大写字母很有效,但对于小写字母和某些“键”,我得到了错误的结果,并且无法找出原因。任何帮助都将不胜感激。

    例子: 如果我试图用17的密钥加密“foo”,它应该返回“wff”,但我的代码只返回“w”。用我写的代码,它是说去位置128,这不是一个字母,但我的代码是说,如果超过122,扣除26。等于并返回“102”,即“f”。这与删除被分配到127有关吗

    #include <cs50.h>
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    #include <stdlib.h>
    
    int main(int argc, string argv[])
    {
      if (argc == 2) {
        int a = atoi (argv[1]);
        int b = a%26;
        printf("plaintext: ");
        //get string
        string s = get_string();
        printf ("ciphertext: ");
            //iterate through string
            for (int i=0, n =strlen(s); i<n; i++) {
                //check if character is a letter
                if ( isalpha (s[i])) {
                    //check if letter is uppercase
                    if (isupper (s[i])) {
                        //calculate position of character in ASCI by adding 'Key'. If character is over 90, decrease character location by 26
                        char c = (s[i] + b);
                        if (c > 90) {
                                char d = c - 26;
                                printf ("%c", d);
                        } else
                        printf("%c", c);
                    } else
                   //For lowercase letters. If character location is over position 122, decrease location by 26
                    {
                        char e = (s[i] + b);
                        if (e>122) {
                                char f = e - 26;
                                printf("%c", f);
                        } else
                            printf("%c", e);
                    }
                } else    //print non letters with no change made
                {
                    printf ("%c", s[i]);
                }
            }
        }
    printf ("\n");
    return 0;
    

    1 回复  |  直到 7 年前
        1
  •  0
  •   M Oehm    7 年前

    对于小写字母,您可能会面临溢出:

    char e = (s[i] + b);
    

    在您的系统上, char 是有符号的,这意味着它可以取128到127之间的值。取小写z,即ASCII 122。将其移动6个位置或更多,则会溢出 . 有符号整数的溢出是未定义的行为。您可以通过生成中间值来解决此问题 int s:

    int e = (s[i] + b);