ex10_8金融应用:货币单位

#include <iostream>
#include <cstdlib>
#include <cctype>
#include <string>
using namespace std;

int myAtoi(const string &s){	//字符串转化为整数
	int n = 0;
	for(auto v : s){
		if(!isdigit(v)){	//如果不是数字字符
			cout << "Invalid string!" << endl;
			exit(EXIT_FAILURE);
		}
	}

	for(auto c : s)
		if(c >= '0' && c <= '9')	//进行转换
			n = 10 * n + (c - '0');
	return n;
}

//分离字符串中整数部分和小数部分
void seperateString(string &first, string &last, const string s){
	for(int i = 0; s[i] != '.'; ++i)	//获取整数部分
		first += s[i];

	for(auto i = s.find('.')+1; s[i] != '\0'; i++)	//获取小数部分
		last += s[i];

}

int main(){
	cout << "Enter an amount in double, for example 11.56: ";
	string amount;
	cin >> amount;
	
	string intergerPart = "", remainderPart = "";	//整数部分和余数部分
	int numberOfOneDollars = 0;
	int remainingAmount = 0;

	if(amount.find('.') != amount.npos){	//如果包含小数部分
		seperateString(intergerPart, remainderPart, amount);
		numberOfOneDollars = myAtoi(intergerPart);
		remainingAmount = myAtoi(remainderPart);
		
	}else{	//如果不包含小数部分
		numberOfOneDollars = myAtoi(amount);
		remainingAmount = 0;
	}
	
	// find the number of quarters in the remaining amount
	int numberOfQuarters = remainingAmount / 25;
	remainingAmount = remainingAmount % 25;

	// find the number of dimes in the remaining amount
	int numberOfDimes = remainingAmount / 10;
	remainingAmount = remainingAmount % 10;

	// find the number of nickels in the remaining amount
	int numberOfNickels = remainingAmount / 5;
	remainingAmount = remainingAmount % 5;

	// find the number of pennies in the remaining amount
	int numberOfPennies = remainingAmount;

	// display results
	cout << "Your amount " << amount << " consists of " << endl <<
		"  " << numberOfOneDollars << " dollars" << endl <<
		"  " << numberOfQuarters << " quarters" << endl <<
		"  " << numberOfDimes << " dimes" << endl <<
		"  " << numberOfNickels << " nickels" << endl <<
		"  " << numberOfPennies << " pennies" << endl;

	return 0;
}

 

转载于:https://www.cnblogs.com/mocuishle/p/7976859.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值