Ejercicio
Operador condicional, positivo y más pequeño
Objetivo
Cree un programa de C# que pida al usuario dos números y respuestas, utilizando el operador condicional (?), lo siguiente:
- Si el primer número es positivo
- Si el segundo número es positivo
- Si ambos son positivos
- Cuál es más pequeño
Código de Ejemplo
using System; // Import the System namespace which contains fundamental classes
class Program // Define the Program class
{
static void Main() // The entry point of the program
{
// Ask the user to enter the first number
Console.Write("Enter the first number: ");
int num1 = int.Parse(Console.ReadLine()); // Read and convert the input into an integer
// Ask the user to enter the second number
Console.Write("Enter the second number: ");
int num2 = int.Parse(Console.ReadLine()); // Read and convert the input into an integer
// Use the conditional operator to check if the first number is positive
string result1 = (num1 > 0) ? "The first number is positive." : "The first number is not positive.";
Console.WriteLine(result1); // Display the result for the first number
// Use the conditional operator to check if the second number is positive
string result2 = (num2 > 0) ? "The second number is positive." : "The second number is not positive.";
Console.WriteLine(result2); // Display the result for the second number
// Use the conditional operator to check if both numbers are positive
string result3 = (num1 > 0 && num2 > 0) ? "Both numbers are positive." : "At least one number is not positive.";
Console.WriteLine(result3); // Display the result if both numbers are positive
// Use the conditional operator to check which number is smaller
string smaller = (num1 < num2) ? "The first number is smaller." : (num2 < num1) ? "The second number is smaller." : "Both numbers are equal.";
Console.WriteLine(smaller); // Display the result for the smaller number
}
}