请帮帮我!我的c ++程序似乎有错误。代码显示关于面额的错误输出,给出输入比索的整数量。编写一个程序,显示1000,500,100,50,20和10比索的账单数量。输出以及所有面额被删除后的剩余金额。
这是我的程序代码。
#include <iostream>
using namespace std;
int main()
{
int a;
cout << "Enter the amount: ";
cin >> a;
cout << "No. of 1000 peso bills: " << a/1000;
cout << "\nNo. of 500 peso bills: " << a%1000/500;
cout << "\nNo. of 100 peso bills: " << a%500/100;
cout << "\nNo. of 50 peso bills: " << a%100/50;
cout << "\nNo. of 20 peso bills: " << a%50/20;
cout << "\nNo. of 10 peso bills: " << a%20/10;
cout << "\n\nThe rest of the amount: " << a%10;
}
输出显示:
Enter the amount: 34757
No. of 1000 peso bills: 34
No. of 500 peso bills: 1
No. of 100 peso bills: 2
No. of 50 peso bills: 1
No. of 20 peso bills: 0
No. of 10 peso bills: 1
The rest of the amount: 7
Process returned 0 (0x0) execution time : 2.156 s
Press any key to continue.
10比索账单的数量必须是0而不是1,我怎么能想更正呢?提前谢谢。
答案 0 :(得分:2)
问题在于数学。由于50不是20的倍数,您需要修复10比索账单的计算:
(a%50-(a%50)/20*20)/10;
这当然只是针对这一具体案例的解决方案。一般来说,如果你有其他账单,事情会更复杂。在你的情况下,你很幸运,因为大多数账单都是所有小账单的完全倍数,其中50/20对是唯一的例外。
一个更通用和可读的解决方案,受到另一个答案的启发:
#include <iostream>
using namespace std;
int main()
{
int a;
cout << "Enter the amount: ";
cin >> a;
cout << "No. of 1000 peso bills: " << a/1000;
cout << "\nNo. of 500 peso bills: " << (a%=1000)/500;
cout << "\nNo. of 100 peso bills: " << (a%=500)/100;
cout << "\nNo. of 50 peso bills: " << (a%=100)/50;
cout << "\nNo. of 20 peso bills: " << (a%=50)/20;
cout << "\nNo. of 10 peso bills: " << (a%=20)/10;
cout << "\n\nThe rest of the amount: " << a%10;
}
答案 1 :(得分:1)
解决问题的一种方法是从总数中减去已用较大账单表示的金额,如下所示:
cout << "No. of 1000 peso bills: " << a/1000;
a %= 1000;
cout << "\nNo. of 500 peso bills: " << a%1000/500;
a %= 500;
cout << "\nNo. of 100 peso bills: " << a%500/100;
a %= 100;
cout << "\nNo. of 50 peso bills: " << a%100/50;
a %= 50;
cout << "\nNo. of 20 peso bills: " << a%50/20;
a %= 20;
cout << "\nNo. of 10 peso bills: " << a%20/10;
a %= 10;
cout << "\n\nThe rest of the amount: " << a;
这将模拟进行更改的过程,方法是在您获得较小的账单时,从您已经提供较大账单的金额中删除。