- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我可以让它打印明文并按键值移动,但是我对如何让字母环绕以及如何将其实现到我的代码中有点困惑。
如有任何建议,我们将不胜感激。
谢谢。
#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/
我正在尝试执行 vagrant up 但一直遇到此错误: ==> default: IOError: [Errno 13] Permission denied: '/usr/local/lib/pyt
我在容器 div 中有一系列动态创建的不同高度的 div。 Varying text... Varying text... Varying text... Varying text.
通过 cygwin 运行 vagrant up 时遇到以下错误。 stderr: /bin/bash: /home/vagrant/.ansible/tmp/ansible-tmp-14872260
今天要向小伙伴们介绍的是一个能够快速地把数据制作成可视化、交互页面的 Python 框架:Streamlit,分分钟让你的数据动起来! 犹记得我在做机器学习和数据分析方面的毕设时,
我是 vagrant 的新手,正在尝试将第二个磁盘添加到我正在用 vagrant 制作的虚拟机中。 我想出了如何在第一次启动虚拟机时连接磁盘,但是当我关闭机器时 然后再次备份(使用 'vagrant
我是一名优秀的程序员,十分优秀!