当我使用数字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");
}
答案 0 :(得分:0)
在for循环中,您应该检查字符是大写,小写还是两者都不是。数字89也是错误的,即“你好”,你可能想要的是65或97,&#39; a&#39;和&#39; A&#39;分别。 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]);
}
}
请注意使用&#39; A&#39;和&#39; a&#39;而不是65和97,这些将在编译时转换为相应的整数文字。还有其他方法可以写这个,这可能不是最干净的方法(例如多个printf()),但它应该说明这是如何工作的,应该这样做。