Python--数学运算--金融应用程序
2017-02-15 13:48
501 查看
前言
这是我在学习Python过程中练习数学运算的一段小程序,尽管看起来很简单,但是编程就是要动手,光看明白是不足够的,脚踏实地一步一步实操才能接近一名开发者或者计算机工程工作者的目标,共勉。题目
用户输入总金额,分别以美元、美分为单位进行对比两种情况结果差异,然后输出一个报告,罗列出等价的货币:美元、两角五分硬币、一角硬币、五分硬币和美分的个数。解题思路
1、提示用户选择美元还是美分为单位输入金额2、转换对应金额为以美分为单位
3、将金额除以100得到美元数,求余得到剩余美分数
4、将剩余美分数除以25得到两角五分硬币个数,求余得到剩余美分数
5、将剩余美分数除以10得到一角硬币个数,求余得到剩余美分个数
6、将剩余美分数除以5得到五分硬币个数,求余得到剩余美分个数,即最终零散美分数
7、返回报告显示结果
source-code1
#!/usr/local/bin/python # encoding: utf-8 ''' test -- python开发学习 -- ex3.8,金融应用 @author: Eric @copyright: 2017 organization_name. All rights reserved. @contact: xj_lin@protonmail.com ''' def choose(): choice = input("Choose the monetary unit between 'dollar' and 'cent'.\n") return choice def currency_change(): choice = choose() if choice == "dollar": total_num_d = eval(input("Please input the total number in dollars:")) #convert amount to cents total_num = int(total_num_d * 100)#可能存在精度损失问题,eg:10.03 * 100 = 1003.9999 9999 9999 9 else: total_num = eval(input("Please input the total number in cents:")) #calculate the number of one dollars dollars_num = total_num // 100 remain_num = total_num % 100 #calculate the number of quarters in the remaining amount quarters_num = remain_num // 25 remain_num = remain_num % 25 #calculate the number of dimes in the remaining amount dimes_num = remain_num // 10 remain_num = remain_num % 10 #calculate the number of nickels in the remianing amount nickels_num = remain_num // 5 remain_num = remain_num % 5 #the remainder pennies number pennies_num = remain_num #report if choice == "dollar": print('Your amount',total_num_d,'consists of:\n\t',dollars_num,'dollars\n\t',quarters_num,'quarters\n\t',dimes_num,'dimes\n\t',nickels_num,'nickels\n\t',pennies_num,'pennies') else: print('Your amount',total_num,'consists of:\n\t',dollars_num,'dollars\n\t',quarters_num,'quarters\n\t',dimes_num,'dimes\n\t',nickels_num,'nickels\n\t',pennies_num,'pennies') if __name__ == "__main__": report = currency_change()
小结
上述代码包含两种情况,即解题思路中提及的单位区分情况,而程序中的所有选择分支也是围绕两种思路进行运行的,选择对应的单位情况便能得到对应的报告结果。本文区分两种情况便是在python数学运算中存在float乘法运算再转为int类型时存在精度的损失,读者不妨自己尝试,代码注释部分有举例。
本文的基本货币单位数量展示是采用贪心算法的思想,每一步取出最大数目的对应货币单位金额,直至达到最小货币单位。
程序使用:eval,input和print这三个基本函数,转义字符\t和\n,其中注意在不同OS平台换行符会有差异,若是Windows平台上是使用\r\n。
- - - - - - - - - - - - - - - - - - - - - - - - -
参考学习:
《Python语言程序设计》——梁勇(著)
不同OS平台换行符解释
相关文章推荐
- [Python标准库]decimal——定点数和浮点数的数学运算
- Python 数学运算
- python读书笔迹 (八) 数据类型和数学运算
- Python numpy随机数生成和数学统计运算[转]
- python基础-数学运算
- Python的常见几道数学运算题
- Python 的数学运算
- python复习笔记[2]——数学运算
- python简单的数学运算.py
- 2.Python - print、variable、基础数学运算
- python基础练习(一)——自定义函数,数学运算,命令行输入
- Python中的数学运算操作符使用进阶
- Python中的数学运算操作符使用进阶
- Python 3基础教程3-数学运算
- python数学运算的类型转换
- shell数学运算 与makefile, python , java
- python学习笔记 1 数学运算
- Python数学运算的一个小算法(求一元二次方程的实根)
- Python内置函数_数学运算类
- Python day03——数学运算、浮点数、布尔类型与布尔表达式