Ejercicio
Dígitos en un número
Objetivo
Cree un programa en C# para calcular cuántos dígitos tiene un entero positivo (pista: se puede hacer dividiendo por 10 varias veces). Si el usuario introduce un entero negativo, el programa debe mostrar un mensaje de advertencia y proceder con el número positivo equivalente.
Por ejemplo:
Número = 32
2 dígitos
Número = -4000
(Advertencia: es un número negativo) 4 dígitos
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 number = int.Parse(Console.ReadLine()); // Reading the number entered by the user
// Check if the number is negative
if (number < 0) // If the number is negative
{
Console.WriteLine("(Warning: it is a negative number)"); // Display the warning message
number = Math.Abs(number); // Convert the number to positive using the Math.Abs() method
}
// Variable to count the digits
int digits = 0;
// Calculate the number of digits by repeatedly dividing the number by 10
while (number > 0) // Loop continues as long as the number is greater than 0
{
number /= 10; // Divide the number by 10
digits++; // Increment the digit count
}
// Display the number of digits
Console.WriteLine(digits + " digits"); // Output the total number of digits
}
}