C++ 让循环找出解决方案?

C++ 让循环找出解决方案?,c++,C++,问题: 一个人携带所有物品需要多少次?每人每次可携带“携带重量”千克的重量 我的解决方案: int main() { int a = 40; // 1st item weight int b = 35; // 2nd item weight int c = 20; // 3rd item weight int maxItemWeight = a; // Max weight item. int times; // Times to carry all the item

问题: 一个人携带所有物品需要多少次?每人每次可携带“携带重量”千克的重量

我的解决方案:

int main()
{
int a = 40; // 1st item weight
int b = 35; // 2nd item weight
    int c = 20; // 3rd item weight

    int maxItemWeight = a; // Max weight item. 
    int times; // Times to carry all the items
    int carryWeight; //How much weight a person can carry at once
    cin >> carryWeight;


    if (maxItemWeight > carryWeight)
        cout << "It's impossible to carry all the items " << endl;
    else {
    if((a + b + c) <= carryWeight)
        times = 1;
    else if ((a+b) <=carryWeight && (a+c) <=carryWeight && (b+c) <=carryWeight)
        times = 2;
    else 
        times = 3;
    cout << "Times to carry all the items: " << carryWeight << endl;
    }
return 0;
}
intmain()
{
int a=40;//第一项重量
int b=35;//第二项重量
int c=20;//第三项重量
int maxItemWeight=a;//最大重量项。
int times;//携带所有项目的时间
int carryWeight;//一个人一次能承受多少重量
cin>>携带量;
如果(maxItemWeight>carryWeight)

cout您似乎在询问是否可以使用数组来允许携带任意数量的“项目”。答案是肯定的:

std::vector<int> item_weights;
unsigned int item_count = 0;
std::cout << "Enter item count:  ";
std::cin >> item_count; // I'll leave the error checking to you to implement
for (unsigned int i = 0; i < item_count; ++i)
{
    std::cout << "Enter weight for item " << (i + 1) << ":  ";
    unsigned int w = 0;
    std::cin >> w; // again error checking should be added
    item_weights.push_back(w);
}

// insert code to retrieve maximum weight that can be carried here

unsigned int max_weight = std::max_element(item_weights.begin(), item_weights.end());
unsigned int total_weight = std::accumulate(item_weights.begin(), item_weights.end(), 0);

// insert your code to determine the number of times it would take to carry all items here
std::向量项的权重;
无符号整数项计数=0;
std::cout>item_count;//我将把错误检查留给您来实现
for(无符号整数i=0;istd::请描述一下问题。只需粘贴代码并说“这很简单”将删除您的问题。这看起来像一个背包问题。请检查我不明白您的问题…?我支持@aardvarkkMy解决方案很简单,但不好。我想问一些提示。如何通过使用for循环或其他方法使此代码通用。@user3088184这里的人不理解此问题。对于那些以前看过,这个想法是显而易见的,但是很显然,仅仅考虑到你的问题,并不是每个人都能理解。(对于一组特定项目的措辞,可能的建议是:“一个人可以携带60公斤。这个人总共需要移动三件物品,分别为40公斤、35公斤和20公斤。如果多件物品可以一次组合携带,需要跑多少次?”)