Caesar Cipher(凯撒密码)C语言程序运行后无输出问题求助
问题原因
- 核心错误是偏移计算逻辑存在两处问题:
- 模运算符号使用错误:你把凯撒密码需要用到的取模运算符
%,误写为了按位与运算符&,二者运算逻辑完全不同,会导致计算出来的字符值是无效的不可见字符,自然无法正常输出。 - 运算符优先级错误:
+的优先级高于%,你没有给模运算部分加括号,就算把&改成%,也会先计算26 + 65或者26 + 97,再对结果取模,完全不符合凯撒密码的偏移逻辑。
- 模运算符号使用错误:你把凯撒密码需要用到的取模运算符
- 次要问题:读取输入的
scanf参数存在缓冲区溢出风险:你定义的message数组长度为80,需要预留1个字节存储字符串结束符\0,所以读取的最多字符数应该设为79,而非80。
修复后的代码
#include <ctype.h> #include <string.h> #include <stdio.h> #include <stdbool.h> int main(void) { int key; bool keyValid = false; while (keyValid == false) { printf("Enter rotation key: "); scanf("%d", &key); if (key >= 0 && key <= 26) { keyValid = true; } else { printf("Error - key must be in range 0 and 26. Try again. "); } } if(keyValid == true) { char message[80]; printf("Enter message to encrypt: "); // 调整读取长度避免越界,去除多余的无效格式符 scanf(" %79[^\n]", message); for(int i = 0; i < strlen(message); i++){ if (isupper(message[i])){ // 修正运算符,添加括号保证运算顺序 message[i] = ((message[i] - 'A' + key) % 26) + 'A'; } else if (islower(message[i])){ message[i] = ((message[i] - 'a' + key) % 26) + 'a'; } } printf("%s\n", message); } return 0; }
补充说明
用字符常量'A'、'a'替代硬编码的65、97,代码可读性更高,也能适配不同字符集的使用场景。
内容的提问来源于stack exchange,提问作者Turk
相关产品推荐
相关产品推荐

