Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我如何从122上的数字中减去?_C#_Loops_Encryption_Integer_Caesar Cipher - Fatal编程技术网

C# 我如何从122上的数字中减去?

C# 我如何从122上的数字中减去?,c#,loops,encryption,integer,caesar-cipher,C#,Loops,Encryption,Integer,Caesar Cipher,我把一堆用户输入的整数分配给变量“c”,并试图从122以上的值中减去。我尝试过很多不同的循环,但我通常会被它卡住,无法工作,或者从所有循环中拿走90个循环。那么,我该如何从122以上的数字中减去90呢 (这适用于凯撒移位加密程序,122为ASCII中的小写字母“z”) List valerie=newlist(); 对于(int i=32;i(Char)(ch)你的代码的哪一部分应该做这个检查?基本上你需要:如果(c>122){c-=90;},那么你只想让它在A-Z上工作,对吗?你根本不需要解码

我把一堆用户输入的整数分配给变量“c”,并试图从122以上的值中减去。我尝试过很多不同的循环,但我通常会被它卡住,无法工作,或者从所有循环中拿走90个循环。那么,我该如何从122以上的数字中减去90呢

(这适用于凯撒移位加密程序,122为ASCII中的小写字母“z”)

List valerie=newlist();
对于(int i=32;i<122;i++)
{
瓦莱丽.加上(i);
}
控制台.WriteLine(“E-Encrypt”);
Console.WriteLine(“D-解密”);
字符串选项=Console.ReadLine();
开关(choice.ToUpper())
{
案例“E”:
控制台。WriteLine(“进入Caesar shift”);
字符串shift=Console.ReadLine();
int offset=int.Parse(移位);
Console.WriteLine(“输入短语”);
字符串短语=Console.ReadLine();
字节[]asciiBytes=Encoding.ASCII.GetBytes(短语);
foreach(字节b以字节为单位)
{ 
int a=转换为int 32(b);
int c=a+偏移量;
控制台写入线(c);
chard=(char)c;
控制台写入线(d);
}

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

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

//Version 2, more compact
int c = a > 122 ? a : 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());
int offset=。。。
字符串短语=。。。;
//规定短语仅包含“A”…'z'ard/或“A”…'z'
字符串编码=新字符串(短语)

。选择(ch=>(Char)(ch)你的代码的哪一部分应该做这个检查?基本上你需要:
如果(c>122){c-=90;}
,那么你只想让它在
A
-
Z
上工作,对吗?你根本不需要解码它-只要减去
'A'
var n=(int)(c-'A')
)然后使用
%
(最后用
(char)
+'A'
转换回来)@Dmytro Shevchenko:谢谢!我编辑了打字稿。很荣幸我把它称为余数运算符而不是模运算符
 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());