Objectivo
Cree un programa de C# para devolver el cambio de una compra, utilizando monedas (o billetes) lo más grandes posible. Supongamos que tenemos una cantidad ilimitada de monedas (o billetes) de 100, 50, 20, 10, 5, 2 y 1, y no hay decimales. Por lo tanto, la ejecución podría ser algo como esto:
¿Precio? 44
¿Pagado? 100
Su cambio es 56: 50 5 1
¿Precio? 1
¿Pagado? 100
Su cambio es 99: 50 20 20 5 2 2
Ejemplo Ejercicio C#
Mostrar Código C#
using System; // Import the System namespace, which contains fundamental classes like Console
class Program // Define the Program class
{
static void Main() // The entry point of the program
{
// Ask the user for the price of the item
Console.Write("Price? ");
int price = int.Parse(Console.ReadLine()); // Read and convert the price to an integer
// Ask the user for the amount paid
Console.Write("Paid? ");
int paid = int.Parse(Console.ReadLine()); // Read and convert the paid amount to an integer
// Calculate the change to be returned
int change = paid - price; // Subtract the price from the paid amount to calculate the change
// Display the total change to be returned
Console.WriteLine($"Your change is {change}:");
// Define an array of available coin and bill denominations
int[] denominations = { 100, 50, 20, 10, 5, 2, 1 }; // Coins and bills in descending order
// Iterate through the denominations array
foreach (int denomination in denominations)
{
// Calculate how many coins/bills of this denomination can be given as change
while (change >= denomination)
{
Console.Write(denomination + " "); // Display the current denomination
change -= denomination; // Subtract the denomination from the remaining change
}
}
// Print a newline after displaying the change
Console.WriteLine();
}
}
Salida
Case 1:
Price? 180
Paid? 500
Your change is 320:
100 100 100 20
Case 2:
Price? 150
Paid? 200
Your change is 50:
50
Case 3:
Price? 85
Paid? 100
Your change is 15:
10 5
Case 4:
Price? 45
Paid? 100
Your change is 55:
50 5
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp