首页 > 解决方案 > 程序没有产生预期的结果

问题描述

我需要计算一个饼干订单有多少容器和盒子。每个容器 75 盒,每盒 24 块饼干。两者都需要有他们指定的数量,所以如果有剩余,我需要说明有多少盒子不能装满一个容器以及剩下多少饼干。在我输入订购的 cookie 总数后,我的代码立即卡住了。

代码的输入是:2001 输出应该是:总共 83 个盒子、1 个容器、8 个剩余的盒子和 9 个剩余的饼干。

这是我的代码:

#include <iomanip>
#include <iostream>

using namespace std;

const int ContBoxes = 75;
const int BoxCookies = 24;

int main() {
    int TotCookies;
    int TotContainers = 0;
    int TotBoxes = 0;
    int RemBoxes = 0;

    cout << "Input number of cookies ordered: ";
    cin >> TotCookies;

    if (TotCookies >= 1800) {
        TotContainers += 1;
        TotCookies -= 1800;
    } else if ((TotCookies >= 24) && (TotCookies < 1800)) {
        RemBoxes += 1;
        TotCookies -= 24;
    } else if (TotCookies < 24) {
    }
    cout << "Your order consists of " << TotContainers << " Containers, "
         << TotBoxes << " Total Boxes, " << RemBoxes
         << " Boxes That couldn't fit in containers, and " << TotCookies
         << " Cookies that couldn't fit in boxes.";

    return 0;
}

标签: c++if-statement

解决方案


这里有一些指导方针,希望能帮助您解决问题。(没有直接给出它)。

  • 当有 10,000 个 cookie 时会发生什么?您的代码将产生多少个“容器”?
  • 对于任何给定的输入,您的代码可以拥有的最大容器总数是多少?
    (提示:您将其增加一,一次)。
  • 现在,对盒子问自己同样的问题......
  • 接下来是另一个提示,但我鼓励你从回答这些开始......

使用整数除法运算符。例如,50/24 会给你 2 - 这正是你在分配给盒子时要寻找的......


推荐阅读