Imagina que pediste comida a domicilio (porque debemos quedarnos en casa), así que crearás un programa al cual ingresarás el valor de los platillos ordenados, obtendrás la suma total de la comida y calcularás un porcentaje de propina. Recuerda que puedes ingresar una cantidad indeterminada de platillos, indica a tu programa cuando calcular el resultado final.
Así quedó mi versión de la calculadora. Le puse también para que metan los impuestos. Recuerden que también hay que pagarlos. 😄
defcalcular_subtotal(cantidad_platillos): valores = [] for _ in range(cantidad_platillos): valor = float(input('Ingresa el costo del platillo o producto: ')) valores.append(valor) subtotal = sum(valores) return subtotal defcalculadora_propipna(subtotal, porcentaje_propina): porcentaje_propina /= 100 propina_calculada = subtotal * porcentaje_propina propina_calculada = round(propina_calculada, 2) return propina_calculada defcalculadora_total(subtotal, propina, porcentaje_impuesto): porcentaje_impuesto /= 100 total_sin_impuestos = subtotal + propina impuestos = total_sin_impuestos * porcentaje_impuesto total = total_sin_impuestos + impuestos total = round(total, 2) return total defmain(): numero_platillos = int(input('\nIngresa la cantidad de platillos y o productos: ')) if numero_platillos > 0: subtotal_platillos = calcular_subtotal(numero_platillos) print(f'Subtotal: {subtotal_platillos}') porc_propina = int(input('\nIngresa el porcentaje de propina: ')) propina = calculadora_propipna(subtotal_platillos, porc_propina) print(f'\nPropina: {propina}') porc_impuesto = int(input('\nIngresa el porcentaje de impuesto en tu región: ')) total = calculadora_total(subtotal_platillos, propina, porc_impuesto) print(f'\nTotal: {total}') else: print('\n\tIngresaste una cantidad de platillo no válida. Ingresa 1 o más platillos.') main() if __name__ == "__main__": main()```
En Python 😃 Calculadora de propinas y valor de platos para “LOS POLLOS HERMANOS” 😉
menu=''' Bienvenido al menu principal de los Pollos Hermanos ''' print(menu) resp=input('Desea ingresar platos a su calculadora de propinas?: ') factura=0while resp == 'si': porcentajeprop=int(input('Ingrese el porcentaje de propina por plato: ')) numplatos=int(input('Ingrese el numero de platos: ')) valor=int(input('Ingrese el valor del plato: ')) valorprop=valor*porcentajeprop/100 valortotplat=numplatos*valor valorpag=valorprop*numplatos+valortotplat print(f'El costo del plato por unidad es {valor}') print(f'El valor de las propinas por plato es {valorprop}') print(f'El costo total de los platos es {valortotplat}') print(f'El valor total mas propinas es {valorpag}') factura=valorpag+factura resp=input('Desea ingresar mas platos a su calculadora de propinas?: ') print(f'Su total a pagar es {factura} Bs')```
#PlatziCodingChallenge Día 13 - Solución al reto con JavaScript
En este reto decidí hacer un ejemplo con Clases y objetos, apreciaria mucho su feedback 😄
https://github.com/pahoalapizco/PlatziCodingChallenge/tree/day13
Código
Implementación
Hola! Como sacas estas imágenes del código?
Done
const AddOrder = options =>{ let countOrder = 0; let plateCost = 25; let percentageTip = 15while(options != '2'){ switch(options){ case'1':{ countOrder++; break; } default: "Escoja una opción correcta"; } options = prompt(`¿Añadir Otro plato? \n1.Si\n2.No\n Platos ordenados:${countOrder}`) } let totalPlates = countOrder; let bill = (countOrder * plateCost); let tip = (percentageTip * bill)/100; let total = bill + tip; console.log(`Total de platos: ${totalPlates}`) console.log(`Valor Plato: $${bill}`) console.log(`Valor Propina: $${tip}`) console.log(`Total a pagar: $${total}`) functiongetOption(){ let options = prompt('Valor Plato:$25.\nPropina: 15%\nQue desa hacer \n1.Añadir Plato/2.Terminar pedido') AddOrder(options); } getOption();
En java:
public class TipCalculator { public static void calculateTip(){ double tip = 0;double total = 0; Scanner scan = new Scanner(System.in);int option;do { System.out.println("Select an option \n 1.Order a new dish \n 2.Calculate Tip \n 3.Exit"); option = scan.nextInt();switch (option){ case1: System.out.println("Dish cost: ");double cost = scan.nextDouble(); total += cost;break;case2: tip = total * 0.10;System.out.println("The tip amount is: " + tip);break;case3: break;default: System.out.println("That's not a vaild option, please try again.");break; } }while (option != 3);System.out.println("Thank you for using the tip caculator. \n total: " + total + "\n tip: "+ tip); } } public class Main { public static void main(String[] args) { TipCalculator.calculateTip(); } }
En python:
""" Programa que recibe el valor de los platillos ordenados y el porcentaje de propina a dar; y calcula e imprime la suma total de la comida, el valor de la propina y el gran total. Program that receives the value of the ordered dishes and the tip percent to give; and calculates and prints the food total sum, the tip vaue and the grand total."""deftip_calculator(): item_price_list = receive_prices() tip_percent = receive_tip_percent() total_prices = sum(item_price_list) tip_value = total_prices*tip_percent/100 total = total_prices + tip_value return total_prices, tip_percent, tip_value, total defreceive_tip_percent():whileTrue: tip_percent = input('Please insert tip percent you want to pay: ') whilenot tip_percent.isdigit(): tip_percent = input('Invalid entry. Please insert a numeric percentage: ') return int(tip_percent) defreceive_prices(): item_price_list = [] stop_asking = 0while stop_asking == 0: item_price = input('Please insert item price: ') whilenot item_price.isdigit(): item_price = input('Invalid entry. Please insert a numeric price: ') if item_price == '0': stop_asking = 1else: item_price_list.append(int(item_price)) return item_price_list if __name__ == "__main__": print('Tip calculator!!! To stop adding items please press \'0\'' ) total_returned_list = tip_calculator() print('The total value of your items is: {:.1f} $\nThe tip value ({}% of tip) is: {} $\nThe GRAND TOTAL is: {} $' .format(total_returned_list[0], total_returned_list[1], total_returned_list[2], total_returned_list[3]))
Calculadora de propina en JavaScript y en Python:
//Calculadora de Propina en JavaScript//"values" es un ArrayfunctiontipCalculator(values, percentage) { let sumValues = values.reduce((a, c) => a + c) return sumValues * percentage } let valores = [] let i = 0do { i++ let valorPlatillo = parseFloat(prompt(`Platillo ${i}: ¿Cuánto valió?`)) valores.push(valorPlatillo) }while(prompt('¿Hay más platillos? (si/no)').toLowerCase() == 'si') let porcentajePropina = parseFloat(prompt('¿Cuál será el procentaje de la propina? (1 - 100%)')) / 100 alert(`La propina es de ${tipCalculator(valores, porcentajePropina)}`)
# Calculadora de Propina en Python# "values" es una listadeftipCalculator(values, percentage): sumValues = 0for i in range(0, len(values)): sumValues += values[i] return sumValues * percentage valores = [] i = 0 otroPlatillo = Truewhile(otroPlatillo): i += 1 valor = float(input('Platillo {}: ¿Cuánto valió? '.format(i))) valores.append(valor) otroPlatillo = (input('¿Hay más platillos? (si/no): ') == 'si') porcentaje = float(input('¿Cuál será el procentaje de la propina? (1 - 100%)? ')) / 100 print('La propina es de {}'.format(tipCalculator(valores, porcentaje)))
Repo con el código en JS, C y C++.
https://github.com/ceporro/PlatziCodingChallenge
En mi país no damos propinas (porque somos tacaños :v), así que calcule la propina como el 10% del total
total = 0.0 while int ( input("Desea pedir comida: \n1. Si \n2. No \nIngrese su opcion: ") ) != 2: precio = float( input("Ingrese el precio de la comida: ")) total = total + precio propina = total * 0.1 print(f"El precio total por las comidas es: {total}") print(f"La propina es: {propina}")
PYTHON
Tip 10% del Total
defMenu(next_dish): cost_sub = 0 count_dish = 0while next_dish isTrue: dish = input('Enter the Dish : ') cost = int(input('Enter the Cost ($) : ')) cost_sub += cost count_dish += 1 next_dish_type = input('Add another dish? Y(es)/N(o): ') if next_dish_type.upper() == 'Y': next_dish = Trueelse: next_dish = False print('-'*30) #Propina tip = cost_sub * 0.10 cost_end = cost_sub * 1.10 print(f"The cost of {count_dish} {('dish' if count_dish == 1 else 'dishes')} is $ {cost_end}0") print(f'The tip is $ {tip}0') if __name__ == "__main__": print(""" SELECT MENU in Python ----------------------------- """) next_dish = True Menu(next_dish)
En JavaScript 😃
let pedi = { inicializar: () => { pedi.template(); pedi.fri = document.getElementById('fri').addEventListener('click', ()=> { pedi.sumPedido(1)}) pedi.que = document.getElementById('que').addEventListener('click', ()=> { pedi.sumPedido(2)}) pedi.rev = document.getElementById('rev').addEventListener('click', ()=> { pedi.sumPedido(3)}) pedi.chi = document.getElementById('chi').addEventListener('click', ()=> { pedi.sumPedido(4)}) pedi.com = document.getElementById('com').addEventListener('click', ()=> { pedi.completar()}) pedi.pago = document.getElementById('pago') pedi.res = document.getElementById('res') }, sumPedido: (num) => { switch (num) { case 1: pedi.cont.push(1) break; case 2: pedi.cont.push(1) break; case 3: pedi.cont.push(1.50) break; case 4: pedi.cont.push(1.25) break; } }, completar: () => { pedi.monto = parseInt(pedi.pago.value) if (pedi.monto == undefined) { pedi.res.innerHTML = 'Ingrese el monto a pagar' } else { for(let i = 0; i < pedi.cont.length; i++) { pedi.sum += pedi.cont[i] } } let propina = (pedi.sum * 10) / 100if (pedi.sum > pedi.monto) { pedi.res.innerHTML = `El monto ingresado es insuficiente para pagar. Su pago es de ${pedi.sum}` } else { pedi.res.innerHTML = `Su pedido completo a pagar es de $${pedi.sum} más propina: ${propina}` } }, template: () => { document.write(`<div> <h1>Menú Pupusas:</h1> <button style="padding:10px" id="fri">frijol</button> <button style="padding:10px" id="que">Queso</button> <buttonstyle="padding:10px"id="rev">Revueltas</button> <button style="padding:10px" id="chi">Chicharón</button><br> <input type="text" id="pago" value="¿Con cuanto pagará?"> <button style="padding:10px" id="com">Completar Pedido</button><br><divid="res">Resultado</div></div>`) }, cont: [], sum: 0, monto: 0 }
Calculadora de propina en Java ☕️ ☕️ 😃
Así quedó mi calculadora de propina, pide al ususrio el número de platillos, el costo de estos y el porcentaje que quiere dejar.
public class CalculadoraPropina { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);System.out.println("Ingresa la cantidad de platillos");int platillos = scanner.nextInt();System.out.println("Ingresa el porcentaje que quieres dejar de propina");int porcentaje = scanner.nextInt();int[] costoPlatillos = new int[platillos];int total = 0;double propina = 0;System.out.println("Ingresa el costo de los platillos");for (int i = 0; i < costoPlatillos.length; i++) { costoPlatillos[i] = scanner.nextInt(); total += costoPlatillos[i]; } propina = (double) total * porcentaje / 100;System.out.println(propina); } }
Resultado del programa

Que cool estos ejercicios la verdad.
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Calculadora de Propina</title></head><style> * { margin: 0; } .contenedor { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; } .section { padding: 0.25rem2rem; } .inputs { display: inherit; align-items: center; padding: 2rem; } .btn { border: 2px solid black; border-radius: 6px; cursor: pointer; } #contra { padding: 020px; width: 95%; } </style><body><divclass="contenedor"><h1style="margin-bottom: 24px;">Calculadora de propinas</h1><buttonstyle="margin-bottom: 24px;"onclick="handleNew()">Agregar platillo</button><p>Porcentaje de propina: <inputid="propina"value='0'/></p><divclass="inputs"><divid="platos"></div></div><buttononclick="revisa()"class="btn">Calcula...</button><divstyle="margin-top: 24px;"id="resultado"></div></div><script>let numeroPlatos = 0functionhandleNew() { const platos = document.getElementById('platos') const newPlato = document.createElement('section') numeroPlatos++ newPlato.className = "section" newPlato.innerHTML = `Precio del platillo $<input id="precio${numeroPlatos}"/>` platos.appendChild(newPlato) } functionrevisa(){ let subTotal = 0for (let i = 1; i <= numeroPlatos; i++){ subTotal = subTotal + parseFloat(document.getElementById(`precio${i}`).value) } let propina = parseInt(document.getElementById('propina').value) let total = subTotal + (propina * subTotal / 100) document.getElementById('resultado').innerHTML = `El total serían $${total.toFixed(2)}` } </script></body></html>
Me olvide de hacer la condición para el subtotal y el total más propina, solamente se le agregaría esto en vez de la linea del mensaje
if (propina === 0) { document.getElementById('resultado').innerHTML = `El subtotal serían: $${subTotal.toFixed(2)} y como no hay propina ese sería el total`
Perdón, me equivoque…
if (propina === 0) { document.getElementById('resultado').innerHTML = `El subtotal serían: $${subTotal.toFixed(2)} y como no hay propina ese sería el total` } else { document.getElementById('resultado').innerHTML = `El subtotal serían: $${subTotal} y entotalmás la propina serían $${total.toFixed(2)}` }
Debería existir una manera de eliminar estos mensajes 😂😂😂
asi me quedo un poco incompleto en c++;
Voy a mejorarlo a futuro cuando mejore mas el lenguaje!!!
#include<iostream>usingnamespacestd; intmain(){ float bill, tip, totaltip; cout << "Valor total de la cuenta? :"; cin >> bill; cout << "porcentage de propina?"; cin >> tip; totaltip = bill * (tip/100.); cout << "la propina para tu total de "<< bill << " es de : "<< totaltip << endl; }
Python:

Output:
++
<let bill = []; let i = 0; do { bill[i] = parseFloat(prompt("How much is the cost of the dish?")); i++; } while ( prompt("Do you want another dish? respond Y(yes) or N(no)").toUpperCase() == "Y" ); const res = bill .reduce((acc, item) => { return (acc = acc + item); }, 0) .toFixed(1); let tip = parseFloat(res * 0.1); console.log(`Amount of tip is ${tip.toFixed(1)}`); >
++
Python
defmain(): pedidos = 2 pedido1 = int(input('Ingresa el valor del primer plato: $ ')) pedido2 = int(input('Ingresa el valor del segundo plato: $ ')) valor_pedido = pedido1 + pedido2 print() print(f'El valor del pedido es de $ {valor_pedido}') print() consulta_propina = input('Deseas dar propina? Y/N : ') consulta_propina = consulta_propina.upper() if consulta_propina == 'Y': propina = float(input('Ingresa el valor del porcentaje de la propina que deseas dar: ')) porcentaje_Propina = (valor_pedido * propina) / 100 print('Propina = ',porcentaje_Propina) total = valor_pedido + porcentaje_Propina print() print(f'El valor total a cancelar es de $ {total}') else: print(f'Has decidido no dar propina, por lo tanto el valor total a pagar es de $ {valor_pedido}') if __name__ == '__main__': main()
const tip = () => { let saucer = parseFloat(prompt('Enter order value')); let askNewSaucer = prompt('Do you want a new order? y/n').toLowerCase(); let COUNT = 1; while(askNewSaucer === 'y') { saucer += parseFloat(prompt('Enter a new order value')); askNewSaucer = prompt('Do you want a new order? y/n').toLowerCase(); COUNT++; } let tip = parseFloat(prompt('What percentage of tip do you want to give? | Remember that it must be greater than 5%')); if (tip < 5) { alert('The tip have be that greater than 5%'); } else { let tipResult = (saucer * tip) / 100let result = (`Total order value: $${saucer} | Tip value: $${tipResult} | Total value: $${saucer + tipResult}`); return(result); } } console.log(tip());
Calculadora de propina
var valorPlatillos = []; var i = 0; const PORC_IMPUESTO = 0.15; const PORC_PROPINA = 0.10; var subtotal = 0.00; vartotal = 0.00; var propina = 0.00; var impuesto = 0.00; const reducer = (accumulator, currentValue) => accumulator + currentValue; do{ valorPlatillos[i] = parseFloat(prompt('Ingrese valor del platillo--->')) i++ }while(prompt('Más plantillos? \n1.Si --> s \n2.No --> n') === 's'); subtotal = valorPlatillos.reduce(reducer).toFixed(2); propina = (subtotal * PORC_PROPINA).toFixed(2); impuesto = (subtotal * PORC_IMPUESTO).toFixed(2); total = ((subtotal * 1 ) + (impuesto * 1) + (propina * 1)).toFixed(2); alert(`Su subtotal es: ${subtotal} Impuestos: ${impuesto}Su propina es: ${propina}Total a pagar: ${total}`)
defmain(): print("Tip Calculator".center(50)) print("*" * 50) print("Enter the amounts you want, to finish leave empty") counter = 1 prices = [] whileTrue: try: user_input = input(f"{counter}. Price: ") user_input = user_input.replace("$", "").strip() if user_input == "": break price = float(user_input) except: print("Invalid value, please try again") else: prices.append(price) counter += 1 subtotal = sum(prices) tip = round(subtotal * 0.15, 2) print("*" * 50) print(f"Tip (15%): ${tip}") print(f"Order subtotal: ${subtotal}") print(f"Order total: ${subtotal + tip}") if __name__ == "__main__": main()
Javascript
const platillos = prompt('Ingresa el numero de platillos a ordenar:') const porcentaje = 0.1functionpropina(platillos) { var total = 0for(i = 0; i < platillos; i++) { var valor = prompt(`Ingresa el valor del platillo ${i+1}:` ) total = total + parseInt(valor) } var tip = total*porcentaje alert(`Total: $${total}. Propina correspondiente: $${tip.toFixed(2)}`) } propina(platillos)
Con Python:
defrun(): control = True platillos = [] suma_total = 0 propina = 0 aux = 0 print('Dame los platillos: ') print('Presiona 0 para finalizar') while control: aux = input(': ') if aux == '0': breakelse: platillos.append(float(aux)) for plato in platillos: suma_total = suma_total + plato print('El total de platillos es: ', suma_total) propina = float(input('Porcentaje de propina: ')) propina = suma_total * (propina/100) print('El total de la propina que vas a dar es de: ', propina) if __name__ == '__main__': run()
En Python, usando Arrays
foodCost = [] addFood = foodCost.append(int(input('dime el valor de la comida: '))) defaddFoodFunction(array): addMoreFood = input('quieres agregar mas comida? Y/N: ').lower() while addMoreFood == 'y': food = foodCost.append(int(input('dime el valor de la comida: '))) addMoreFood = input('quieres agregar mas comida? Y/N: ').lower() endFoodCost = calcEnd(foodCost) print(f'tu total es {endFoodCost}') calcPropina(endFoodCost) defcalcEnd(array): suma = 0for i in foodCost: suma += i return suma defcalcPropina(endFoodCost): user = int(input('que porcentaje de propina quieres dar? ')) propina = (endFoodCost * user) // 100 print(f'la propina es {propina}') addFoodFunction(foodCost)
Reto 13: Calculadora de propina
Repositorio del reto: PlatziCodingChallengeRepo
GitHub pages: PlatziCodingChallengePages
Listo 👍🏻
Mi solución en Python:
lista_precio = [] defcalcular_recibo(): precio_total = sum(lista_precio) propina = round(precio_total * .10,2) precio_final = precio_total + propina print('=== B O L E TA ===') print('Total de platillos pedidos: ', len(lista_precio)) print('Precio total de los platillos: S/.', precio_total) print('Propina S/: ', propina) print('Precio Final S/ : ', precio_final) print('') print('Gracias por su visita') print('') defrun(): precio_basico = 10 precio_especial = 18 precio_ejecutivo = 25whileTrue: print(" === Restaurante === ") opcion = int(input(''' Escoge tus platillo: [1] basico S/ 10.0 [2] especial S/ 18.0 [3] ejecutivo S/ 25.0 [4] calcular recibo [5] salir ''')) if opcion == 1: print("Opcion 1, S/") lista_precio.append(precio_basico) elif opcion == 2: print("Opcion 2") lista_precio.append(precio_especial) elif opcion == 3: print("Opcion 3") lista_precio.append(precio_ejecutivo) elif opcion == 4: calcular_recibo() elif opcion == 5: breakelse: print("Opcion no valida") if __name__ == '__main__': run()
propina - Python
defpropina(): print("Bienvenido. Ingresa tus platillos y el valor de cada uno") print("") print("Platillo: Sopa") print("Costo: 10") print("") print("Aterminar solo escribe: salir en la opcion platillo") food_list =[] price_list =[] whileTrue: print("") food = input("Platillo: ") if food == "salir": break price = float(input("Costo: ")) food_list.append(food) price_list.append(price) subTotal = sum(price_list) tip = round(subTotal * 0.15,2) total = round(subTotal + tip,2.) for i in range(len(food_list)): print(f"{price_list[i]}-----{food_list[i]}") print("-----------") print(f"Subtotal: {subTotal}") print(f"Propina: {tip}") print(f"Total: {total}") if __name__ == "__main__": propina()