How do I calculate power-of in C#?

后端 未结 8 1567
别跟我提以往
别跟我提以往 2021-01-01 08:08

I\'m not that great with maths and C# doesn\'t seem to provide a power-of function so I was wondering if anyone knows how I would run a calculation like this:



        
8条回答
  •  Happy的楠姐
    2021-01-01 08:56

    I'm answering this question because I don't find any answer why the ^ don't work for powers. The ^ operator in C# is an exclusive or operator shorten as XOR. The truth table of A ^ B shows that it outputs true whenever the inputs differ:

    Input A Input B Output
    0 0 0
    0 1 1
    1 0 1
    1 1 0

    Witch means that 100 ^ 3 does this calculation under the hood:

    hex   binary
    100 = 0110 0100 
      3 = 0000 0011
    ---   --------- ^
    103 = 0110 0111
    

    With is of course not the same as Math.Pow(100, 3) with results to one million. You can use that or one of the other existing answers.


    You could also shorten your code to this that gives the same result because C# respects the order of operations.

    double dimensions = 100 * 100 / Math.Pow(100, 3); // == 0.01
    

提交回复
热议问题