0

请帮我!我的 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,我该如何纠正这个问题?提前致谢。

4

2 回答 2

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;
}
于 2013-10-06T12:33:31.753 回答
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;

这将通过在您获得较小的账单时删除您已经提供较大账单的金额来模拟进行更改的过程。

ideone 上的演示

于 2013-10-06T12:39:41.930 回答