c++ - 无法在 C++ 中找到两个项目之间的差异

标签 c++ modulo cmath

让我先声明一下,我对 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/

相关文章:

c++ - 在C++中打印pow()函数的精确值

c++ - 为什么 CRC 和 C++ 代码版本的 CRC 计算不同?

c++ - 关于 operator[] 的编译错误

c# - C++ 将 UTF 字节数组转换为字符串

ios - 使用余数运算符(模)并转换为 Int 返回 false 值

c++ - 为什么 C++ 中的 pow() 返回负数

c++ - 在qt中更改svg的颜色

java - BigInteger 模 '%' 运算和小于/大于运算

python - 分数取模。分数类

c++ - cos返回错误值?