【发布时间】:2019-12-09 10:19:59
【问题描述】:
当我使用负数表示 -1 之类的移位并使用字符“a”时,我应该得到 'z',但我得到的是 `。我该如何解决这个问题?
using System;
using System.IO;
namespace CaesarCipher
{
class Program
{
public static char cipher(char ch, int key)
{
if (!char.IsLetter(ch))
{
return ch;
}
char d = char.IsUpper(ch) ? 'A' : 'a';
return (char)((((ch + key) - d) % 26) + d);
}
public static string Encipher(string input, int key)
{
string output = string.Empty;
foreach (char ch in input)
output += cipher(ch, key);
return output;
}
public static string Decipher(string input, int key)
{
return Encipher(input, 26 - key);
}
static void Main(string[] args)
{
bool Continue = true;
Console.WriteLine(" Ceasar Cipher");
Console.WriteLine("-------------------------\n");
while (Continue)
{
try
{
Console.WriteLine("\nType a string to encrypt:");
string UserString = Console.ReadLine();
Console.Write("\nShift: ");
int key = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nEncrypted Data: ");
string cipherText = Encipher(UserString, key);
Console.WriteLine(cipherText);
Console.Write("\n");
Console.WriteLine("Decrypted Data:");
string t = Decipher(cipherText, key);
Console.WriteLine(t);
Console.WriteLine("\nDo you want to continue?");
Console.WriteLine("Type in Yes to continue or press any other key and then press enter to quit:");
string response = Console.ReadLine();
Continue = (response == "Yes");
}
catch (FormatException ex)
{
Console.WriteLine("You entered a bad operation, try another one");
}
}
}
}
}
凯撒密码
键入要加密的字符串: 你好,你好吗?
移位:1
加密数据: ifmmp ipx bsf zpv?
解密数据: 你好,你好吗?
您要继续吗? 输入 Yes 继续或按任何其他键,然后按 enter 退出: 是的
键入要加密的字符串: 你好,你好吗?
移位:-1
加密数据: gdkkn gnv `qd xnt?
解密数据: 你好,你好吗?
您要继续吗? 输入 Yes 继续或按任何其他键,然后按 enter 退出:
【问题讨论】:
-
答案似乎很明显:您需要翻转。英文字母只有大约 26 个字符宽。如果低于或高于该值,则需要返回另一端。您应该考虑用字符制作一个数组,而不是只做 ASCII 数学。这不仅会支持更多语言,而且您将避免小写字母变成大写字母,反之亦然,偏移量大。只有 +/-7 可以将小“a”变成大“Z”。 IIRC 罗马人不使用小写字母,所以他们对此问题不大。
-
return (char)((((ch + key) - d) % 26) + d);等价于:return (char)(ch + key);,我猜这不是你想要的。
标签: c# encryption visual-studio-2019