判断在C++中是否可以根据给定的成本范围和数量范围得到一个比率


概念

根据给定的成本范围(从lowCost到upCost)和数量范围(从lowQuant到upQuant),确定是否可以获得给定的比率r,其中r=成本/数量,并且lowCost <= 成本 <= upCost以及lowQuant <= 数量 <= upQuant。

输入

lowCost = 2, upCost = 10,
lowQuant = 3, upQuant = 9
r = 3

输出

Yes

解释

这里,成本 = r * 数量 = 3 * 3 = 9,其中成本在[1, 10]之间,数量在[2, 8]之间。

输入

lowCost = 15, upCost = 31,
lowQuant = 6, upQuant = 13
r = 8

输出

No

解释

这里,成本 = r * 数量 = 8 * 6 = 48,其中成本不在[15, 31]之间,虽然数量在[6, 13]之间。

方法

根据上述公式,可以很容易地推导出以下等式:

成本 = 数量 * r。其中,r表示成本和数量之间的比率。

根据上述等式,可以很容易地推导出逻辑。验证数量的每个值与r的乘积,并且应该注意的是,如果乘积的任何值在lowCost和upCost之间,则答案是“是”,否则是“否”。

示例

 在线演示

// C++ program to find if it is
// possible to get the ratio r
#include <bits/stdc++.h>
using namespace std;
// Here, returns true if it is
// possible to obtain ratio r
// from given cost and
// quantity ranges.
bool isRatioPossible1(int lowCost1, int upCost1,
int lowQuant1, int upQuant1,
int r1){
   for (int i = lowQuant1; i <= upQuant1; i++){
      // Used to calculate cost corresponding
      // to value of i
      int ans1 = i * r1;
      if (lowCost1 <= ans1 && ans1 <= upCost1)
      return true;
   }
   return false;
}
// Driver Code
int main(){
   int lowCost1 = 2, upCost1 = 10,
   lowQuant1 = 3, upQuant1 = 9,
   r1 = 3;
   if (isRatioPossible1(lowCost1, upCost1,
      lowQuant1, upQuant1, r1))
      cout << "Yes";
   else
      cout << "No";
   return 0;
}

输出

Yes

更新于:2020年7月24日

60 次浏览

开始你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.