问题是“花5元买了100个纽扣,一个金属纽扣5角,一个玻璃纽扣1角,三个塑料纽扣5分,求每种纽扣分别买了多少?”
于是我用了
#include<iostream>
using namespace std;
int metal, plastic, glass;
int buttons(int x,int y)
{
int money_p, money_m;
x *= 10;
//cout << x << " ";
plastic = y - y % 6;
//cout << plastic << " ";
money_p = plastic / 6;
//cout << money_p << " ";
metal = (x - money_p) / 5;
//cout << metal << " ";
money_m = metal * 5;
//cout << money_m << " ";
glass = x - money_p - money_m;
//cout << glass << " ";
for (; plastic + metal + glass != 100; money_p--)
{
plastic=money_p*6;
//cout << plastic << " ";
metal = (x - money_p) / 5;
//cout << metal << " ";
money_m = metal * 5;
//cout << money_m << " ";
glass = x - money_p - money_m;
//cout << glass << " ";
for (; plastic + metal + glass != 100 && metal >= 0; metal = metal - 1)
{
if (money_m + money_p + plastic != x)
{
cout << plastic << " ";
money_m = metal * 5;
cout << metal << " ";
glass = x - money_m - money_p;
cout << glass << " ";
}
}
};
return 0;
}
int main()
{
int money, total;
cout << "请输入金额:";
cin >> money;
cout << "请输入纽扣个数:";
cin >> total;
buttons(money, total);
cout << "共买了" << metal << "个金属纽扣," << glass << "个玻璃纽扣," << plastic << "个塑料纽扣。";
return 0;
}
但实际上代码运行到plastic=90, metal=6, glass=5就会停止循环,输出"共买了5个金属纽扣,5个玻璃纽扣和五个塑料纽扣"的结果