gpt4 book ai didi

c - C语言中简单的凯撒密码,无需用户输入

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

我需要编写一个程序,将特定消息(S M Z V Q O P I V)存储在一组char变量中,然后在将解密后的消息一次输出一个字符之前,应用移位值为8。通过使用包含多个%c说明符的格式字符串,输出应看起来像一个字符串。

我只能找到需要用户输入的代码示例,尽管我刚刚对其进行了修改,使其具有已经具有所需值的变量,但我仍在努力理解代码应如何遍历字符串的意义-即ch = ch-'Z'+'A'= 1,这对于在字母之间使用运算符实际上意味着什么?

到目前为止,这就是我所拥有的,尽管代码输出[Ub ^ YWXQ ^作为加密的消息-有什么办法可以纠正应该为字母的字符? Z应该变成H吗?

#include <stdio.h>
#include <stdlib.h>

int main()
{
char message[] = "SMZVQOPIV";
int i;
int key = 8;

printf("%s", message);

char ch= message [i];

for(i = 0; message[i] !='\0';++i)
{
ch = message[i];

if(ch >= 'A' && ch <= 'Z'){
ch = ch + key;
if (ch > 'z'){
ch = ch - 'Z' + 'A' - 1;
}
message[i] = ch;
}
}

printf("Encrypted Message: %s", message);
return 0;
}


有人可以简短地向我介绍代码的外观和原因吗?自从我进行任何编程以来已经有一段时间了,并且我主要使用Python,所以在C语言中有些失落。

最佳答案

#include <stdio.h>
#include <stdlib.h>

int main()
{
char message[] = "SMZVQOPIV";
int i;
int key = 8;

printf("%s\n", message);
/*
* "printf("%s", message);" -> "printf("%s\n", message);"
* you have to print a newline('\n') by yourself,
* it's not automatic as "print" in python
*/


/*
* There was a "char ch= message [i];"
* unecessary and it gives error(i is not initialised)
*/

for (i = 0; message[i] != '\0'; ++i)
{

char ch = message[i];
/*
* "ch = message[i];" -> "char ch = message[i];"
* when you define an object in C, you have to specify its type
*/

if (ch >= 'A' && ch <= 'Z') {
ch = ch + key;
if (ch > 'Z') {
/*
* Main error here, but just a blunder
* "if (ch > 'z') {" -> "if (ch > 'Z') {"
* Upper case is important ;), 'Z' is 90 in decimal,
* 'z' is 122
*/

ch = ch - 'Z' + 'A' - 1;
}
message[i] = ch;
}
}

printf("Encrypted Message: %s", message);
return 0;
}

关于c - C语言中简单的凯撒密码,无需用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58902698/

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