让我先声明一下,我对 C++ 还是非常陌生,希望让事情尽可能简单。我的数学也很糟糕。
大多数情况下,我正在寻找是否有人可以帮助我的代码,以便它始终给出正确的结果。除了在一种情况下,我大部分时间都用它来做我想做的事。
我的代码试图找出某人购买了多少包热狗威纳和多少包热狗面包。然后它会告诉用户他们可以从中制作多少热狗,以及他们将拥有多少剩余的 weiner 或面包。假设一包威纳有 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;
}
有了这个,如果包子和 weiners 的比例相同,或者如果 weiner 比包子多,我总能得到正确的答案。
由于我设置 total 和/或 leftOverBuns 的方式(第 9 行和第 11 行),我永远无法得到剩余面包数量的正确答案。我知道如果不能修改我当前的代码,那么必须有一种更简单的方法来执行此操作,但我很困惑。
我知道我几乎留下了零符号,所以如果你想要一些,请告诉我!
最佳答案
你把事情搞得太复杂了。试试这个:
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 block 决定函数是否报告剩余的面包或 weiners。
关于c++ - 无法在 C++ 中找到两个项目之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30960967/