怎么减去除以122的数

本文关键字:的数 | 更新日期: 2023-09-27 18:12:42

我有一堆用户输入的整数分配给变量'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);
                }

怎么减去除以122的数

您必须使用模块化算术:不只是为每个字符添加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());

要么我误解了你的问题,要么你只是需要检查你的输入…

//Version 1
int c = a;
if(a > 122)
    c = c - offset;
//Version 2, more compact
int c = a > 122 ? a : a + offset;