Grupo
Conceptos básicos control de flujo en C#
Objectivo
Escriba 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.
Haga esto de dos maneras diferentes en el mismo programa: usando "if" y usando el operador condicional (?).
Ejemplo de ejercicio en C#
Mostrar código C#
using System;
namespace AbsoluteValueCalculator
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
double x = double.Parse(Console.ReadLine());
double absoluteValueIf = x;
if (x < 0)
{
absoluteValueIf = -x;
}
Console.WriteLine("Using 'if': The absolute value of {0} is {1}", x, absoluteValueIf);
double absoluteValueConditional = (x < 0) ? -x : x;
Console.WriteLine("Using conditional operator: The absolute value of {0} is {1}", x, absoluteValueConditional);
}
}
}
Output
//Example 1 (Positive Number):
Enter a number: 25
Using 'if': The absolute value of 25 is 25
Using conditional operator: The absolute value of 25 is 25
//Example 2 (Negative Number):
Enter a number: -12
Using 'if': The absolute value of -12 is 12
Using conditional operator: The absolute value of -12 is 12
//Example 3 (Zero):
Enter a number: 0
Using 'if': The absolute value of 0 is 0
Using conditional operator: The absolute value of 0 is 0
Código de ejemplo copiado
Comparte este ejercicio de C#