0

変数「c」に割り当てられたユーザー入力整数の束があり、122 を超える値から減算しようとしています。さまざまなループを試しましたが、通常、機能しないか、90 を奪ってしまいます。それらすべてから。では、122 を超える数から 90 を正確に取り除くにはどうすればよいでしょうか。

(これはシーザー シフト暗号化プログラム用で、122 は ASCII の小文字の 'z' です)

        List<int> valerie = new List<int>();
        for (int i = 32; i < 122; i++)
        {
            valerie.Add(i);
        }

        Console.WriteLine("E - Encrypt");
        Console.WriteLine("D - Decrypt");

        string choice = Console.ReadLine();

        switch (choice.ToUpper())
        {
            case "E":


                Console.WriteLine("Enter Caesar shift.");
                string shift = Console.ReadLine();
                int offset = int.Parse(shift);
                Console.WriteLine("Enter phrase.");
                string phrase = Console.ReadLine();
                byte[] asciiBytes = Encoding.ASCII.GetBytes(phrase);
                foreach(byte b in asciiBytes)
                { 
                    int a = Convert.ToInt32(b);
                    int c = a + offset;
                    Console.WriteLine(c);
                    char d = (char)c;
                    Console.WriteLine(d);
                }
4

2 に答える 2

2

モジュラー算術を使用する必要があります。各文字に a を追加するだけでなく、剰余offsetを取るので、 Linqの助けを借りてそれを置くことができます。

 int offset = ...
 String phrase = ...;

 // Providing that the phrase constains 'A'..'z' ard/or 'a'..'z' only
 String encoded = new String(phrase
   .Select(ch => (Char) (ch <= 'Z' ? 
            (ch + offset) % 26 + 'A' : // note "% 26"
            (ch + offset) % 26 + 'a')) // note "% 26"
   .ToArray());
于 2015-09-14T11:41:45.590 に答える
0

私はあなたの質問を誤解したか、あなたの入力を確認する必要があります...

//Version 1
int c = a;
if(a > 122)
    c = c - offset;

//Version 2, more compact
int c = a > 122 ? a : a + offset;
于 2015-09-14T11:41:10.770 に答える