求助 :关于Liang《c++程序设计》中一个课后习题的问题
题目是计算给定金额的货币数量,比如$11.56处理后为11个一美元,2个25美分,和1个十美分还有一美分。下面试代码
程序代码:
#include<iostream> using namespace std; int main() { cout<<"enter an aomunt in double ,for example 11.56 :"; double amount; cin>>amount; // remainingAmount用来保留运算后的剩余的货币金额 int remainingAmount = static_cast<int>(amount * 100); // "/"计算当前最大面值,“%”求未表示出的金额数(即被忽略的金额) int numberOfOneDollars = remainingAmount / 100; remainingAmount =remainingAmount % 100; int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; int numberOfDimes =remainingAmount / 10; remainingAmount = remainingAmount % 10; int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; int numberOfPennies = remainingAmount; cout<<"Your amount "<< amount <<" consists of \n "; /*规范化输出,使计数为0的不显示,计数为1的单位为单数 */ if(numberOfOneDollars){ if(numberOfOneDollars==1) cout<<"\t"<< numberOfOneDollars <<" dollar \n" ; else cout<<"\t"<< numberOfOneDollars <<" dollars \n" ; } if(numberOfQuarters) { if(numberOfQuarters==1) cout<<"\t"<< numberOfQuarters << " quarter \n" ; else cout<<"\t"<< numberOfQuarters << " quarters \n" ; } if(numberOfDimes) { if(numberOfDimes==1) cout<<"\t"<< numberOfDimes << " dime \n" ; else cout<<"\t"<< numberOfDimes << " dimes \n" ; } if(numberOfNickels) { if(numberOfNickels==1) cout<<"\t"<< numberOfNickels << " nickel \n" ; else cout<<"\t"<< numberOfNickels << " nickels \n" ; } if(numberOfPennies) { if(numberOfPennies==1) cout<<"\t"<< numberOfPennies << " pennise"; else cout<<"\t"<< numberOfPennies << " pennises"; } return 0[local]1[/local][local]2[/local] }
我用了几组数字(11.56和11.11)进行了测试,其中一组结果不是我预期的效果,后来查看Liang博士的网上习题答案,可悲的是他的程序运行后也有点问题,我比较了下,我们的算法是一样的。
希望,有做过或者技术娴熟的朋友能来帮忙解答一下。万分感谢
测试截图 11.11 结果不正确。