ToInt32 w c#

0

Witam :)
chcialem sie dowiedziec na jakiej zasadzie dziala konwertowanie liczby zmiennoprzecinkowej na liczbe calkowita za pomoca funkcji IntTo32

Mam taki program:
float a = 1.3f;
float b = 0.02f;
int c = (int)(a / b);
int d = Convert.ToInt32(a / b);

        Console.WriteLine("Pokaż c = " + c);
        Console.WriteLine("Pokaż d = " + d);

        Console.ReadKey();

I w pierwszym lini zwraca liczbę 64, a w drugiej 65, gdy zmienie 1.3f na 1.4f to wyniki są równe

1

Rzutowanie obcina część ułamkową.

Konwersja -> https://msdn.microsoft.com/en-us/library/ffdk7eyz(v=vs.110).aspx

2

Możesz sobie prześledzić całą funkcję:

public static int ToInt32(double value) {
	if (value >= 0) {
		if (value < 2147483647.5) {
			int result = (int)value;
			double dif = value - result;
			if (dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++;
			return result;
		}
	}
	else {
		if (value >= -2147483648.5) {
			int result = (int)value;
			double dif = value - result;
			if (dif < -0.5 || dif == -0.5 && (result & 1) != 0) result--;
			return result;
		}
	}
	throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
// Źródło: http://referencesource.microsoft.com/#mscorlib/system/convert.cs,10cd63a0dc4a7c4c,references
3

Matematycznie to jest równe 65.0, ale ze względu na niedokładność liczb zmiennoprzecinkowych wynik zapewne wychodzi minimalnie mniejszy niż 65. Rzutowanie obcina wszystko po przecinku, więc zostaje 64.

Natomiast według DOKUMENTACJI funkcji Convert.ToInt32:

Return Value
Type: System.Int32

value, rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

1 użytkowników online, w tym zalogowanych: 0, gości: 1