如何从大于 122 的数字中减去?
How do I subtract from numbers over a 122?
我将一堆用户输入的整数分配给了一个变量 '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);
}
要么我误解了你的问题,要么你只需要检查你的输入...
//Version 1
int c = a;
if(a > 122)
c = c - offset;
//Version 2, more compact
int c = a > 122 ? a : a + offset;
你必须使用 modular 算法:不只是给每个字符加一个 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());
我将一堆用户输入的整数分配给了一个变量 '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);
}
要么我误解了你的问题,要么你只需要检查你的输入...
//Version 1
int c = a;
if(a > 122)
c = c - offset;
//Version 2, more compact
int c = a > 122 ? a : a + offset;
你必须使用 modular 算法:不只是给每个字符加一个 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());