[英]Caesar cipher in C - unexpected problems
我的凱撒密碼遇到了意想不到的問題。 Caesar 是通過將每個字母移動 n 個數字來加密文本。 所以如果它是 1,abc 將是 bcd。 我在用 C 語言編寫的程序上工作,但它對某些字符、常規字母的工作很奇怪,盡管它應該是正確的。 這是問題語法:
for (int i = 0; i < strlen(text); i++)
{
if (text[i] != ' ')
{
// printf("\n%i\n", key);
text[i] = text[i] + key;
if (text[i] > 122)
{
text[i] = text[i] + 97 - 122;
}
}
}
我最后通過做這個數學來結束。 你能幫我看看有什么問題嗎?
編輯:這段代碼很好,問題在於命令行參數的處理。
用96
代替97
問題解決
所以當你環繞時,實際上增加了 1 個額外的值,想想這個;
------------------------------------------
a | b | c | d | . . . x | y | z |
--------------------------------------------
97 | 98 | 99 | 100 | . . .120 | 121 | 122 |
-------------------------------------------
嘗試使用 'a' , 'b' , .. .. .. ,'z' 像這樣而不是它們的實際值
在 char 中使用' '
單引號可為您提供整數值,即 ASCII 值
這是代碼:
char c;
for (int i = 0; i < strlen(text); i++)
{
if (text[i] != ' ')
{
// printf("\n%i\n", key);
c=text[i];
text[i] = text[i] + key;
if(c >='a' && c <='z' && text[i] >'z')
text[i] = text[i] + 'a' -1 - 'z' ;
if(c >='A' && c <= 'Z' && text[i] > 'Z')
text[i] = text[i] + 'A' -1 - 'Z' ;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.