让我先说一下,我仍然是C ++的新手,并希望尽可能保持简单。我在数学方面也非常糟糕。
大多数情况下,我正在寻找是否有人可以帮助我的代码,以便始终提供正确的结果。除了一种情况外,我主要是让它做我想做的事。
我的代码正在尝试找出有多少热狗蛋糕包以及有多少热狗包的购买包。然后它告诉用户他们可以从中获得多少热狗,以及他们将拥有多少剩余的weiners或包子。假设一个weiners包含12个,包装包含8个,这是我到目前为止所提出的:
#include <iostream>
#include <cmath>
using namespace std;
void hotdog(int a, int b){ //a = weiner packages, b = bun packages
int weiners = 12 * a;
int buns = 8 * b;
int total = (weiners + buns) - (weiners - buns);
int leftOverWeiners = total % weiners;
int leftOverBuns = total % buns;
int totalHotDogs = total / 2;
cout << "You can make " << totalHotDogs << " hotdogs!" << endl;
if (leftOverWeiners > 0){
cout << "You have " << leftOverWeiners << " weiners left over though." << endl;
}else if (leftOverBuns > 0){
cout << "You have " << leftOverBuns << " buns left over though." << endl;
}
}
int main(){
int a;
int b;
cout << "Let's see how many hotdogs you can make!" << endl;
cout << "How many weiner packages did you purchase?: ";
cin >> a;
cout << "How many bun packages did you purchase?: ";
cin >> b;
hotdog(a, b);
return 0;
}
有了这个,我可以随时得到正确的答案,如果面包与面包的比例是相同的,或者是否有比面包更多的面包。
由于我设置总计和/或左侧的方式(第9,11行),我将永远无法得到剩余包子的数量的正确答案。我知道必须有一个更简单的方法来做到这一点,如果不是一种方法来修改我当前的代码,但我很难过。
我知道我几乎没有留下符号,所以如果你想要一些,请告诉我!
答案 0 :(得分:2)
你让它太复杂了。试试这个:
if(weiners > buns)
{
cout << "You can make " << buns << " hotdogs!" << endl;
cout << "with " << weiners-buns << " weiners left over" << endl;
return;
}
cout << "You can make " << weiners << " hotdogs!" << endl;
if(buns > weiners)
{
cout << "with " << buns-weiners << " buns left over" << endl;
}
较小的{buns,weiners}是热狗的数量,if-then块确定该功能是否会报告剩余的包子或者weiners。
答案 1 :(得分:0)
#include <iostream>
void hotdog( int weinerspackages, int bunspackages ){
const int weinersPerPackage = 12;
const int bunsPerPackage = 8;
const int totalweiners = weinerspackages * weinersPerPackage;
const int totalbuns = bunspackages * bunsPerPackage;
int leftoverweiners = 0;
int leftoverbuns = 0;
int amountOfHotdogs = 0;
if( totalweiners > totalbuns ){
leftoverweiners = totalweiners - totalbuns;
amountOfHotdogs = totalbuns;
leftoverbuns = 0;
}
else if( totalbuns > totalweiners ){
leftoverbuns = totalbuns - totalweiners;
amountOfHotdogs = totalweiners;
leftoverweiners = 0;
}
else{
amountOfHotdogs = totalweiners;
leftoverweiners = 0;
leftoverbuns = 0;
}
std::cout << "You can make: " << amountOfHotdogs << " Hotdogs" << std::endl;
std::cout << "Leftover Weiners: " << leftoverweiners << " || Leftover Buns: " << leftoverbuns << std::endl;
}
int main(){
int PackagesW = 8;
int PackagesB = 12;
hotdog( PackagesW, PackagesB );
system("pause");
return 0;
}
注意:可以使用较少的变量来执行此操作,我声明了这一数量的变量,以便更容易理解数字代表的内容。
假设只需要一个人制作一个热狗,你可以找到你拥有的最少的成分,你可以制作的热狗数量将受到该成分量的限制,这就是为什么{ {1}}取较小值的值。如果两者的数量相等,那么amountOfHotdogs
可以取任何数量。
只有数量较多的成分会有剩余物,因此amountOfHotdogs
时leftoverweiners = totalweiners - totalbuns;
,反之亦然。