gpt4 book ai didi

c - caesar.c 的奇怪输出

转载 作者:行者123 更新时间:2023-11-30 15:28:01 24 4
gpt4 key购买 nike

来 self 的 caesar.c 文件的代码

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


int main(int argc, string argv[])
{
// get a string from the user, a non-negative integer.
if (argc != 2 || atoi(argv[0]) < 0)
{
printf("Usage: ./caesar cyphertext\n");
return 1;
}

// create the cyphertext.
int cyphertext = atoi(argv[1]);

// declare plaintext input.
string plaintext = GetString();

// get the plaintext encrypted using the key.
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
if (plaintext[i] > 'A' && plaintext[i] <= 'Z')
{
plaintext[i] = (plaintext[i] - 'A' + cyphertext) % 26;
}
else if (plaintext[i] >= 'a' && plaintext[i] < 'z')
{
plaintext[i] = (plaintext[i] - 'a' + cyphertext) % 26;
}
}
{
// print out the results of the cypher and plaintext.
printf("%s\n", plaintext);
}
return 0;
}

输出我输入 ./caesar 13,然后在下一行输入单词“hello”。然后 Hello 返回几个小盒子,里面有小字母和数字。我不能复制并粘贴确切的字符。

编辑:

感谢您的帮助。我按照您的帮助进行了清理,现在当我运行 check50 程序时

check50 2014/x/pset2/caesar caesar.c

我收到以下错误:

:( encrypts "BARFOO" as "EDUIRR" using 3 as key
\ expected output, but not "EAUIRR\n"

然而,当我以 3 作为键运行单词 BARFOO 时,我实际上得到的输出为EAUIRR。

最佳答案

您在凯撒加密中犯了错误。

plaintext[i] = (plaintext[i] - 'A' + cyphertext) % 26;

应该是

plaintext[i] = 'A' + ((plaintext[i] - 'A' + cyphertext) % 26);

plaintext[i] = (plaintext[i] - 'a' + cyphertext) % 26;

应该是

plaintext[i] = 'a' + ((plaintext[i] - 'a' + cyphertext) % 26);

说明:

让我们考虑 plaintext[i]="h"的情况。

plaintext[i] - 'a' 

等于 7。('h' - 'a')

(plaintext[i] - 'a' + cyphertext) % 26

等于 20。((7 + 13) % 26)

代码为20的字符是控制代码“DC4”,不可打印。

这就是为什么您会看到“其中有小字母和数字的小方框”。

您可以通过将代码“a”添加到 20 来解决此问题。

关于c - caesar.c 的奇怪输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26748737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com