简体   繁体   English

将代码转换为C#

[英]Convert Code to C#

I was looking into random number generators and found pseudo code for one: 我正在研究随机数生成器,发现其中一个的伪代码:

function Noise1(integer x)
    x = (x<<13) ^ x;
    return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);    
end function

I would like to convert this into C# but I get all kinds of error like invalid expressions and ")" expected. 我想将其转换为C#,但会收到各种错误,例如无效表达式和预期的“)”。 This is what I have so far how can I convert it? 到目前为止,这是我该如何转换?

double Noise(int x) {
    x = (x<<13) ^ x;
    return ( 1.0 - ((x * (x * x * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);
}

Thanks. 谢谢。

我不知道您是从哪种语言开始的,但是在C#中,十六进制常量的外观应该有所不同:将7fffffff更改为0x7fffffff

You can use the .Net Framework random object 您可以使用.Net Framework随机对象

Random rng = new Random();
return rng.Next(10)

But I strongly recommend you to read this article from Jon Skeet about random generators 但我强烈建议您阅读Jon Skeet的这篇有关随机生成器的文章

http://csharpindepth.com/Articles/Chapter12/Random.aspx http://csharpindepth.com/Articles/Chapter12/Random.aspx

EDIT: tested and reported a non-null sequence 编辑:测试并报告了非空序列

  1. Convert your hexadecimal constants to use "0x" prefix 将您的十六进制常量转换为使用“ 0x”前缀

  2. Convert int <-> double carefully 仔细转换int <-> double

  3. Split the expression to make it a little bit more readable 拆分表达式以使其更具可读性

Here's the code and unit test (strange results though): 这是代码和单元测试(尽管结果奇怪):

using System;

namespace Test
{
    public class Test
    {
        public static Int64 Noise(Int64 x) {
             Int64 y = (Int64) ( (x << 13) ^ x);

             Console.WriteLine(y.ToString());

             Int64 t = (y * (y * y * 15731 + 789221) + 1376312589);

             Console.WriteLine(t.ToString());

             Int64 c = t < 0 ? -t : t; //( ((Int32)t) & 0x7fffffff);

             Console.WriteLine("c = " + c.ToString());

             double b = ((double)c) / 1073741824.0;

             Console.WriteLine("b = " + b.ToString());

             double t2 = ( 1.0 - b);
             return (Int64)t2;
        }

        static void Main()
        {

           Int64 Seed = 1234;

           for(int i = 0 ; i < 3 ; i++)
           {
               Seed = Noise(Seed);
               Console.WriteLine(Seed.ToString());
           }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM