现有n块砖,要由n人一次搬完,假定男人一次可以搬4块,女人一次可以搬3块,两个小孩搬1块,计算这n人中男人、女人和小孩的人数。输入人数和砖数n,输出可能的解决方案。
我自己用C写了一个,但是无法运行,网上找的C++的那个就对了,我感觉这两串代码都一样啊,这是为啥?
还有为什么在中间的时候要用 XYZ重新规定一下数据?否则结果就结果不对。
#include <stdio.h>
int main()
{
int n;
int man,woman,children;
int x,y,z;
scanf("%d",&n);
for ( man = 0; man <= n/4; man++)
{
for (woman = 0; woman <= n/3; woman++)
{
children = 2 * (n - 4 * man - 3 * woman);
if (children>0 && children == n - man - woman )
{
x = man; y = woman; z = children;
printf("man%d\nwoman%d\nchildren%d\n",man,woman,children);
}
}
}
if( x==0||y==0||z==0)
printf("no result");
return 0;
}
可以运行的代码
#include <iostream>
#include <cmath>
#include<stdlib.h>
using namespace std;
int main()
{
int men, women, children;
int n;
int x, y, z;
cin >> n;
for (men = 0; men <= n / 4; men++)
{
for (women = 0; women <= n / 3; women++)
{
children = 2 * (n - 4 * men - 3 * women);
if (children>0 && children == n - men - women)
{
x = men; y = women; z = children;
cout << "men" << men << endl;
cout << "women" << women << endl;
cout << "children" << children << endl;
}
}
}
if (x == 0 || y == 0 || z == 0)
cout << "no result!" << endl;
system("pause");
return 0;
}