OPERADORES ARITMÉTICOS
Un operador es un símbolo especial que indica al compilador que debe efectuar una operación matemática o lógica.
CSharp reconoce los siguientes operadores:
| Category | Name | Syntax Example | Overloadable? | |
| Primary | Grouping | (a+b) | No | |
| Member | A.B | No | ||
| Struct pointer member access | A→B | No | ||
| Method call | f(x) | No | ||
| Post increment | c++ | Yes | ||
| Post decrement | c– | Yes | ||
| Constructor call | c = new Coord(); | No | ||
| Array stack allocation | int* c = stackalloc int[10] | No | ||
| Struct size retrieval | sizeof (int) | No | ||
| Arithmetic check on | checked {byte c = (byte) d;} | No | ||
| Arithmetic check off | unchecked {byte c = (byte) d;} | No | ||
| Unary | Positive value | +10 | Yes | |
| Negative value | -10 | Yes | ||
| Not | !(c==d) | Yes | ||
| Bitwise complement | ~(int x) | Yes | ||
| Pre increment | ++c | Yes | ||
| Pre decrement | –c | Yes | ||
| Type cast | (myType)c | No | ||
| Value at address | int* c = d; | No | ||
| Address value of | int* c = &d; | No | ||
| Type operators | Type equality / compatibility | a is String | No | |
| Type retrieval | typeof (int) | No | ||
| Arithmetic | Multiplication | c*d | Yes | |
| Division | c/d | Yes | ||
| Remainder | c%d | Yes | ||
| Addition | c+d | Yes | ||
| Subtraction | c-d | Yes | ||
| Shift bits right | c»3 | Yes | ||
| Shift bits left | c«3 | Yes | ||
| Relational and Logical | Less than | c<d | Yes | |
| Greater than | c>d | Yes | ||
| Less than or equal to | c⇐d | Yes | ||
| Greater than or equal to | c>=d | Yes | ||
| Equality | c==d | Yes | ||
| Inequality | c!=d | Yes | ||
| Bitwise and | c&d | Yes | ||
| Bitwise or | c | d | Yes | |
| Logical and | c&&d | No | ||
| Logical or | c | d | No | |
| Conditional | int c=(d<10) ? 5:15 | No | ||
De momento nos concentramos en los operadores aritmeticos, pero dejamos esta tabla de operadores para usarla a lo largo del curso.
Recordar que en c# cuando se dividen dos enteros, csharp trunca la parte residual, es decir si se realiza la siguiente operación:
float alfa= 10 / 3;
desplegar alfa→sale 3 en pantalla
Es decir csharp truncó el residuo de la division entre enteros, no importa el tipo de variable (primero se realiza la operación a la derecha y luego carga la variable a la izquierda, es decir para cuando quiere cargar la variable el residuo ya no existe) para arreglar este problema usar el siguiente metodo:
float alfa= 10/3.0; observar que ya no esta dividiendo enteros, sino un entero entre un decimal.
El operador modulo o remanente (%) devuelve el residuo entero de una división entre enteros, ejemplo;
// área de declaración int o float alfa; // área de operaciones alfa = 23 % 4; // área de despliegue desplegar alfa; -> El resultado en pantalla es 3 Otro ejemplo; alfa = 108 % 10; desplegar alfa; -> El resultado en pantalla es 8
Para resolver los problemas de potencias y raíces se usan ciertas instrucciones especiales que proporciona el lenguaje llamadas funciones matemáticas, en chsarp existe toda una librería o mas correctamente dicho, una clase especializada en instrucciones o funciones matemáticas (System.Math).
Recordar que todas las funciones reciben uno o más datos o valores y regresan siempre un resultado, una de estas funciones matemáticas es:
a) Potencias por ejemplo 5² se resuelve usando el objeto MATH y su metodo Pow(base,exp).
System.field o metodo
Public Fields
E Represents the natural logarithmic base, specified by the constant, e.
PI Represents the ratio of the circumference of a circle to its diameter, specified by the constant, π.
Public Methods
Abs Overloaded. Returns the absolute value of a specified number.
Acos Returns the angle whose cosine is the specified number.
Asin Returns the angle whose sine is the specified number.
Atan Returns the angle whose tangent is the specified number.
Atan2 Returns the angle whose tangent is the quotient of two specified numbers.
Ceiling Returns the smallest whole number greater than or equal to the specified number.
Cos Returns the cosine of the specified angle.
Cosh Returns the hyperbolic cosine of the specified angle.
Exp Returns e raised to the specified power.
Floor Returns the largest whole number less than or equal to the specified number.
IEEERemainder Returns the remainder resulting from the division of a specified number by another specified number.
Log Overloaded. Returns the logarithm of a specified number.
Log10 Returns the base 10 logarithm of a specified number.
Max Overloaded. Returns the larger of two specified numbers.
Min Overloaded. Returns the smaller of two numbers.
Pow Returns a specified number raised to the specified power.
Round Overloaded. Returns the number nearest the specified value.
Sign Overloaded. Returns a value indicating the sign of a number.
Sin Returns the sine of the specified angle.
Sinh Returns the hyperbolic sine of the specified angle.
Sqrt Returns the square root of a specified number.
Tan Returns the tangent of the specified angle.
Tanh Returns the hyperbolic tangent of the specified angle.
Fuente: documentacion de NET FRAMEWORK
Para el ejemplo a seguir, el de potencias esta función ocupa dos valores o datos( base y exp) ambos de tipo double y regresa un resultado también de tipo double, ejemplo;
double pot;
pot = System.Math.Pow(5,2);
desplegar pot;
b) Raíces solo recordar la ley de exponentes que dice:
TAREAS PROGRAMACION C# NET
1.- expresar las siguientes funciones en notacion algebraica de csharp
OPERADOR CAST
Se puede forzar un dato, variable o una expresión a convertirse o cambiarse a un nuevo tipo de dato.
El operador cast realiza este proceso es decir convierte datos, variables o expresiones a un nuevo tipo de dato, su formato es:
(nvotipo) dato, var, exp;
Ejemplo:
// declaración int alfa; // Asignación alfa=20; // Cambio de tipo (double)alfa;
Ejemplo:
(int)3.1416;
En este ejemplo se está convirtiendo un float a int recordar que en este caso ya no se tendrán los decimales.
Como nota importante este operador resuelve los dos problemas pendientes:
- El de la división entre enteros.
- El tipo de dato especifico que requieren las funciones.
Ejemplos:
a) // Declaración float alfa; // Operación alfa = float (23)/5; // Pero en estos casos es preferible usar un puntodecimal alfa=23/5.0;
En toda división recordar agregar a uno de los dos valores el (.0), solo que los dos elementos sean variables entonces usar el operador cast con una de ellas.
b)// Declaración double potencia; // Operación potencia = Pow ( (double)5, (double)3);
Como se observa en el ejemplo se puede usar Pow() directamente con los datos, argumentos o parámetros requeridos si estos son numéricos pero transformándolos con el operador cast.
Recordar que es Pow ←- P GRANDOTA.
Esto también va a permitir evaluar expresiones matemáticas de manera mas directa y sencilla, solo recordando usar un Pow() por cada potencia y cada raíz de la ecuación, ejemplo:
// área de declaración de variables double y, x; // área de captura de datos capturar el valor de x; // área de operaciones y = 3 * Pow(x, (double)3) - Pow(x, (1/3.0)) + 4 * Pow(x, (double)2 ); // área de despliegue de resultados desplegar x, y
TAREAS PROGRAMACION C# NET POW ():