题目描述
用小于等于n元去买100只鸡,大鸡5元/只,小鸡3元/只,还有1/3元每只的一种小鸡,分别记为x只,y只,z只。编程求解x,y,z所有可能解。
输入描述:
测试数据有多组,输入n。
输出描述:
对于每组输入,请输出x,y,z所有可行解,按照x,y,z依次增大的顺序输出。
示例1
输入
40
输出
x=0,y=0,z=100
x=0,y=1,z=99
x=0,y=2,z=98
x=1,y=0,z=99
代码:
一开始写的代码…这个代码有点弱….
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int x, y, z;
int n;
while(cin >> n){
int maxn = 3 * n;
float sum = 0.0;
for(x = 0; x < maxn; ++x){
for(y = 0; y < maxn; ++y){
for(z = 0; z < maxn; ++z){
if(x + y + z == 100){
sum = 5 * x + 3 * y + 1.0 / 3.0 * z;
if(sum <= n){
printf("x=%d,y=%d,z=%d\n", x, y, z);
}
}
}
}
}
}
return 0;
}
改进后:
#include <iostream>
#include <fstream>
using namespace std;
const int num = 100;
int main(){
int x, y, z, n;
while(cin >> n){
for(x = 0; x < num; ++x){
for(y = 0; y < num - x; ++y){
z = num - x - y;
if(15 * x + 9 * y + 1 * z <= 3 * n){ //不等式两边同乘3,解决小数问题
printf("x=%d,y=%d,z=%d\n", x, y, z);
}
}
}
}
return 0;
}