Ejercicio
Muchos Números Y Suma
Objectivo
Cree un programa en C# que le pida al usuario varios números (hasta que ingrese "fin" y muestre su suma). Cuando la ejecución va a terminar, debe mostrar todos los números ingresados, y la suma nuevamente, de la siguiente manera:
Introduzca un número: 5
Suma = 5
Introduzca un número: 3
Suma = 8
Introduzca un número: end
Los números son: 5 3
La suma es: 8
Ejemplo Ejercicio C#
Mostrar Código C#
using System; // Import the System namespace for basic functionality
class Program // Define the main class
{
static void Main() // The entry point of the program
{
double sum = 0; // Variable to store the sum of the numbers
string input; // Variable to store user input
string numbersEntered = ""; // String to store the entered numbers
// Prompt user for numbers until they enter "end"
Console.WriteLine("Enter numbers (type 'end' to stop):");
// Continue looping until user enters "end"
while (true)
{
Console.Write("Enter a number: ");
input = Console.ReadLine(); // Read user input
if (input.ToLower() == "end") // Check if input is "end"
break; // Exit the loop if "end" is entered
// Try to convert the input to a double and add it to the sum
if (double.TryParse(input, out double number))
{
sum += number; // Add the number to the sum
numbersEntered += number + " "; // Append the number to the list of entered numbers
Console.WriteLine($"Sum = {sum}"); // Display the current sum
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number.");
}
}
// Display the entered numbers and the total sum once "end" is entered
Console.WriteLine($"The numbers are: {numbersEntered.Trim()}");
Console.WriteLine($"The sum is: {sum}");
}
}
Salida
Case 1:
Enter numbers (type 'end' to stop):
Enter a number: 1.5
Sum = 1.5
Enter a number: 2.3
Sum = 3.8
Enter a number: 3.7
Sum = 7.5
Enter a number: -4.8
Sum = 2.7
Enter a number: 5.0
Sum = 7.7
Enter a number: end
The numbers are: 1.5 2.3 3.7 -4.8 5
The sum is: 7.7
Case 2:
Enter numbers (type 'end' to stop):
Enter a number: -1.1
Sum = -1.1
Enter a number: -2.2
Sum = -3.3
Enter a number: -3.3
Sum = -6.6
Enter a number: -4.4
Sum = -11
Enter a number: -5.5
Sum = -16.5
Enter a number: end
The numbers are: -1.1 -2.2 -3.3 -4.4 -5.5
The sum is: -16.5
Case 3:
Enter numbers (type 'end' to stop):
Enter a number: 10.0
Sum = 10
Enter a number: 20.0
Sum = 30
Enter a number: 30.0
Sum = 60
Enter a number: 40.0
Sum = 100
Enter a number: 50.0
Sum = 150
Enter a number: end
The numbers are: 10 20 30 40 50
The sum is: 150
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp