Cubi73
Cubi73

Reputation: 1951

Exponent operator

I discovered, that I can write 1E5 or 1e5 instead of 100000. Is there a way to use this operator/method/something with variables? I know I can use Math.Pow(10, 5);, but I wanted to know if this this E works with variables, too.

Upvotes: 3

Views: 8725

Answers (5)

heijp06
heijp06

Reputation: 11808

You could use the bit shift operator to do something similar:

int i = 1;
Console.WriteLine(i << 3); // 8

The bitshift operator << does exactly the same thing as the E in 1E5. Only in base 2, not 10.

Upvotes: 2

poke
poke

Reputation: 388443

The e is not an operator. Is is part of the real literal syntax of the C# language. It is evaluated when the code is parsed and can only be used to express a constant literal.

Just like you can use suffixes f to denote a float, or d to denote a double, the XeY syntax allows you to define doubles with the value X * 10^Y. It’s simply meant as a convenience when you’re writing code with constant numbers.

Here are some more examples on what you can do with all these different syntaxes, and which type and constant literal they are equivalent to:

var a = 2e5;      // (double) 200000
var b = 2.3e3;    // (double) 2300
var c = 13f;      // (single) 13
var d = 53d;      // (double) 53
var e = 1.2e3f;   // (single) 1200
var f = 2.3m;     // (decimal) 2.3
var g = 1.23e-4m; // (decimal) 0.000123

However, none of that is exposed to the .NET runtime, it is all evaluated at compile time and stored as exposed as constant literals—there is absolutely no difference between the short syntax and the full constant. As such, this functionality is not available for variables which only exist at run-time. If you need to exponentiate those, you will have to use other methods, for example myVariable * 10e5.

Upvotes: 9

wizulus
wizulus

Reputation: 6363

The E notation is only for constants. Math.Pow(x, 5) is the only built-in way to exponent a variable.

EDIT

However, Math.Pow accepts doubles and returns a double, so if you want to exponent an integer, you should look at this answer: this answer

Upvotes: 7

Lajos Arpad
Lajos Arpad

Reputation: 77083

The 1E5 notation refers to a numeric value, which, by definition is a value. Your variable might have a numeric value provided that it is of numeric type (like double), but it can change its value (this is why it is called a variable). So, your variable is a placeholder for values, not a value and you cannot use this notation, as it is reserved only for values.

Upvotes: 1

Sarima
Sarima

Reputation: 749

The use of "e" as an operator(ish) is restricted to constants only.

If this worked on variables, it would cause havoc...eg:

Hello = 10;
H = 1;
llo = 5;

x = Hello

Does "x" now equal 10 or 1e5?

Math.Pow(x,y) is your best bet.

Upvotes: 0

Related Questions