当我使用数字 4-22 时,输出很不稳定,我不明白为什么。非常感谢您的帮助,我也想知道为什么这不起作用。
#include<cs50.h>
#include<stdio.h>
#include<string.h>
int main(void)
{
int shifts;
int enc;
printf("What is your message ");
string message = get_string();
printf("By how many letters do you want to shift?");
scanf("%d",&shifts);
for(int i=0;i<strlen(message);i++)
{
enc=((message[i] - 89)+shifts)%26;
printf("%c",enc + 89);
}
printf("\n");
}
最佳答案
在 for 循环中,您应该检查字符是大写、小写还是两者都不是。数字89也是错误的,那就是“Y”,你可能想要的是65或97,分别是“a”和“A”。 for 循环应更改为:
#include <ctype.h> // For isupper()/islower()
for(int i = 0; i < strlen(message); i++)
{
if(isupper(message[i])) { // Check if current char is uppercase
enc=((message[i] - 'A')+shifts)%26; // Apply cipher
printf("%c",enc + 'A');
} else if(islower(message[i])) { // Check if current char is lowercase
enc=((message[i] - 'a')+shifts)%26; // Apply cipher
printf("%c",enc + 'a');
} else { // Print char without change
printf("%c", message[i]);
}
}
请注意使用“A”和“a”而不是 65 和 97,这些将在编译时转换为相应的整数文字。还有其他方法可以编写此代码,这可能甚至不是最干净的方法(例如多个 printf()),但它应该说明这是如何工作的以及应该完成的。
关于谁能告诉我凯撒算法有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44877733/