Pergunta

in C#, an int data type has a maximum value of 2,147,483,647 and a float maximum value is 340282300000000000000000000000000000000

what causes these data types to have maximum values, where do those numbers come from?

Foi útil?

Solução

They come from the fact that those types are limited to a certain number of bits. In the case of 2,147,483,647, we're talking about a 32-bit signed value. For 32-bits there are only 4,294,967,294 possible combinations of 1s and 0s. Half of those representations will be negative values, and half will be positive. (Well, actually, one of them will be 0, which is neither negative or positive, but you get the point.)

Let's look at a simple example. Let's take a 2-bit number. There are 4 possible combinations:

00 = 0
01 = 1
10 = 2
11 = 3

We can have 4 non-negative values. Or, if we want to include negatives, we can have 2 negatives, 0, and 1 positive:

00 = 0
01 = 1
10 = -2
11 = -1

For 3 bits, we get:

000 = 0
001 = 1
010 = 2
011 = 3
100 = 4
101 = 5
110 = 6
111 = 7

For signed values, we'd get:

000 = 0
001 = 1
010 = 2
011 = 3
100 = -4
101 = -3
110 = -2
111 = -1

To understand how the negative values are created you can read the Wikipedia article on 2s compliment format.

To understand floating point is more complicated, but it comes down to the same reason, ultimately. The number of bits used to represent the number limits how many values can be represented. (If you're interested you can read about IEEE 754 floating point format.)

Outras dicas

Because those types are supposed to take up a single word (under most architectures), which allows arithmetic operations to be extremely fast due to ISA-level support. You can absolutely make a "true" integer or rational type (this is the approach taken by many functional and scripting languages), but this may reduce performance in certain programs.

Licenciado em: CC-BY-SA com atribuição
scroll top