判斷在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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP