Ejercicio
Valor absoluto
Objetivo
Escribir un programa en C# para calcular (y mostrar) el valor absoluto de un número x: si el número es positivo, su valor absoluto es exactamente el número x; si es negativo, su valor absoluto es -x.
Hazlo de dos maneras diferentes en el mismo programa: usando "if" y usando el "operador condicional" (?)
Código de Ejemplo
using System; // Importing the System namespace to use Console functionalities
class Program
{
// Main method where the program execution begins
static void Main()
{
// Prompt the user to enter a number
Console.Write("Enter a number: ");
int x = int.Parse(Console.ReadLine()); // Read and convert the input to an integer
// Using if statement to calculate absolute value
int absoluteValueIf = x; // Initially assume the absolute value is x
if (x < 0) // Check if the number is negative
{
absoluteValueIf = -x; // If negative, make it positive by negating it
}
// Display the result using the 'if' method
Console.WriteLine($"Absolute value using 'if': {absoluteValueIf}");
// Using the conditional operator (?) to calculate absolute value
int absoluteValueConditional = (x < 0) ? -x : x; // If x is negative, make it positive using ? operator
// Display the result using the conditional operator method
Console.WriteLine($"Absolute value using conditional operator: {absoluteValueConditional}");
}
}