CS50 PSET 2个凯撒错误的结果
问题描述:
以为我已经完成了凯撒,但运行CHeck50的时候,我的代码,因此失败:加密“barfoo”为“yxocll”采用23键 输出无效ASCII文本 登录 运行./caesar 23 ... 发送输入barfoo ... 检查输出 “密文:yxocll” ...CS50 PSET 2个凯撒错误的结果
任何人都可以看到什么错我的代码?它似乎对大写字母很好,但小写字母和某些'键',我得到错误的结果,并不能找到原因。任何帮助将不胜感激。
例如:如果我尝试使用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;
}
答
用小写字母,你可能会面临溢出:
char e = (s[i] + b);
在您的系统,char
签订后,这意味着它可以从− 128到127的值。取小写字母z,即ASCII 122.将其移位6位或更多,并且溢出char
。有符号整数的溢出是未定义的行为。你可以通过设置你的中间值来解决这个问题int
s:
int e = (s[i] + b);
你正在检查字符是否是一个字母的字符,这是大小写。为什么要测试它的数值呢? –
因为如果大写字母在ASCII位置90上方,即超过大写字母Z,它将返回一个不正确的非大写字母。我需要检查它的位置和减去26,以便A-Z环绕。 – Shaun
但它不会按字母顺序排列,对不对? –