下面列出了我应该做的事情。程序运行但我无法在输出中输出正确的数字。我认为逻辑是正确的,但它不起作用。
我们获得了#饼干,盒子将=饼干数除以24,如果有额外的饼干>比0我们添加一个框。
我们拿#箱子,额外的箱子是> 0我们添加一个集装箱。
然后我们有了集装箱和箱子的总数。
我不知道为什么它不起作用,并且在过去3个小时内一直坚持这个问题,最后放弃并寻求帮助。
一盒饼干可容纳24个饼干,一个容器可容纳75盒饼干 饼干。编写一个程序,提示用户输入总数 cookies,盒子里的饼干数量,以及饼干盒子的数量 容器。程序然后输出框的数量和数量 用于运送饼干的容器。请注意,每个框必须包含指定的 cookie的数量,每个容器必须包含指定的数量 框。如果最后一盒cookie包含少于指定的数量 cookies,你可以丢弃它并输出剩余的cookie数量。同样的, 如果最后一个容器包含少于指定框的数量,则可以 丢弃它并输出剩余的盒子数量。因为这是一章 选择控制结构,如果没有cookie或没有框 剩下的剩余饼干或剩余的盒子不得输出。
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
// Declare variables
int cookies, extraCookies;
int boxes,totalBoxes;
int leftOverBoxes;
int containers;
boxes = (cookies/24);
extraCookies = cookies%24;
containers = boxes/75;
leftOverBoxes = boxes%75;
// Ask for the user input ( doesnt make sense because we are given the capacities)
cout << " How many cookies do you have ?"<< endl;
cin >> cookies;
cout << " You have this many cookies: " << cookies << endl;
cout << " How many cookies can you fit in one box ?" << endl;
cin >> cookies;
cout << " How many cookie boxes can you fit into a container ?" << endl;
cin >> boxes;
// Computer number of boxes needed
if(extraCookies > 0)
totalBoxes = (boxes + 1);
cout <<" We need this many boxes:" << totalBoxes << endl;
if(leftOverBoxes > 0)
containers = ( containers + 1);
cout << "We need this many containers: " << containers << endl;
return 0;
}
答案 0 :(得分:0)
C ++从上到下阅读。请允许我为您的代码添加注释,解释正在发生的事情:
#include<iostream>
#include<cmath>
using namespace std; // Bad practice, by the way
int main()
{
// Declare variables
int cookies, extraCookies; // cookies = 0, extraCookies = 0
int boxes,totalBoxes; // boxes = 0, totalBoxes = 0
int leftOverBoxes; // leftOverBoxes = 0
int containers; // containers = 0
boxes = (cookies/24); // boxes = 0/24 = 0, this line does nothing
extraCookies = cookies%24; // extraCookies = 0%24 = 0, this line does nothing
containers = boxes/75; // containers = 0/75 = 0, this line does nothing
leftOverBoxes = boxes%75; // leftOverBoxes = 0%75 = 0, this line does nothing
// Ask for the user input ( doesnt make sense because we are given the capacities)
cout << " How many cookies do you have ?"<< endl;
cin >> cookies;
cout << " You have this many cookies: " << cookies << endl;
cout << " How many cookies can you fit in one box ?" << endl;
cin >> cookies; // You throw away how many cookies the user has, and rewrite it with how many cookies fit in one box
cout << " How many cookie boxes can you fit into a container ?" << endl;
cin >> boxes;
// Computer number of boxes needed
if(extraCookies > 0) // 0 > 0 == false
totalBoxes = (boxes + 1);
cout <<" We need this many boxes:" << totalBoxes << endl;
if(leftOverBoxes > 0) // 0 > 0 == false
containers = ( containers + 1);
cout << "We need this many containers: " << containers << endl;
return 0;
}
您在从用户那里获取输入之前计算boxes
,extraCookies
,containers
和leftOverBoxes
。它们都被初始化为0。
您应该在收到用户的输入后计算出来。
将代码视为一系列指令。如果你还没有大量的饼干,你无法弄清楚你需要多少个盒子。