#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;
}