gpt4 book ai didi

c - 让凯撒密码环绕起来

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

我可以让它打印明文并按键值移动,但是我对如何让字母环绕以及如何将其实现到我的代码中有点困惑。

如有任何建议,我们将不胜感激。

谢谢。

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

//Gets number of user arguments and the key.
int main (int argc, string argv[]) {
if(argc != 2) {
printf("try again\n");
}
//Converts string to int.
int key = atoi(argv[1]);

//Will store the chars + key.
int result;

printf("Please enter what you would like to encrypt: ");

//Gets plaintext from user.
string plainText = get_string();

//Iterates over the user's input, checking for the case of each char.
for (int i = 0; i <= strlen(plainText); i++) {
if (toupper(plainText[i]) || tolower(plainText[i])) {
result = plainText[i];
}
//Checks if i'th char is a letter and shifts it.
if (isalpha(plainText[i])) {
result = plainText[i + key];
}
}
printf("%c", result);
}

最佳答案

做到这一点的最巧妙的技巧之一是使用模 %运算符。

现在谈论您的代码,

for (int i = 0; i <= strlen(plainText); i++) {
if (toupper(plainText[i]) || tolower(plainText[i])) {
result = plainText[i];
}
//Checks if i'th char is a letter and shifts it.
if (isalpha(plainText[i])) {
result = plainText[i + key];
}
}
printf("%c", result);

这段代码对我来说毫无意义。我猜你的第一个 if 条件是为了区分非字母字符,所以 if 条件可能类似于 if (! isalpha(plainText[i]) ,

那么你的第二个条件是如果它是字母表,则将键添加到字符上。应该是这样的

if (isalpha (plainText[i])) {
if (islower(plainText[i])
result = ((plainText[i] - 'a') + key) % 26 + 'a';
else
result = ((plainText[i] - 'A') + key) % 26 + 'A';

}

上述逻辑说明::首先检查字母是小写还是大写,这样就可以使其在 0 的范围内。至26 ,然后你将 key 与 key 的模相加,这样它就可以循环回到 0,然后你再次通过添加 'a' 的值将其转换为 ascii。

例如如果plainText[i] = 'x' (ascii value 120)key = 5 ,那么

plainText[i] =  120
plaintext[i] - 'a' = 23
(plaintext[i] - 'a') + key = 28 // Out of 0-25 alphabet range
((plaintext[i] - 'a') + key) % 26 = 2 // Looped back
(((plaintext[i] - 'a') + key) % 26) + 'a' = 99 (ascii value for 'c')

如您所见,我们得到了 c添加5后至x

最后打印的位置应该在循环内,否则它只会打印最后一个输入,这是不正确的。

我希望我所做的一切能够帮助您,同时牢记 CS50 的荣誉准则。我还建议您在他们的论坛中提出这些问题,因为他们是一个更知识渊博的社区,可以使用 <cs50.h>

此外,享受 CS50,它是帮助您入门的最佳 CS 类(class)之一;)

关于c - 让凯撒密码环绕起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41669119/

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