我试图将某个const值分配到特定条件。
例如,我有3个const值
const double highDiscount = 0.3;
const double midDiscount = 0.2;
const double lowDiscount = 0.1;
成本最高的产品应获得高折扣,而中间成本应获得midDiscount,最低成本应获得lowDiscount。
因此,我尝试使用if-else语句通过特定条件分配const。
double discount;
if (acost > bcost && acost > ccost)
{
discount = highDiscount;
if ( bcost < ccost)
{
discount = midDiscount;
}
else if ( ccost < bcost )
{
discount = lowDiscount;
}
}
使用我的输出代码
cout << "acost has a" discount*100 << "% discount" << endl;
cout << "bcost has a" discount*100 << "% discount" << endl;
cout << "ccost has a" discount*100 << "% discount" << endl;
应产生以下结果
acost有30%的折扣
ccost有20%的折扣
bcost有10%的折扣
不幸的是,当我编译我的代码时,事实证明所有的a,b和c都有10%的折扣而不是分配的const值。
我错过了一些重要的重点吗?
答案 0 :(得分:1)
在产品类中,添加&lt;操作
bool operator< (const product &other) const {
return cost < other.cost;
}
然后创建一个包含所有产品的向量。
vector<product> products;
products.push_back(product1);
products.push_back(product2);
products.push_back(product3);
对产品向量进行排序(按成本排序)
std::sort(products.begin(), products.end());
只需将折扣应用于已排序的元素
products[0].discount = lowDiscount;
products[1].discount = midDiscount;
products[2].discount = highDiscount;
这比嵌套的if语句更容易阅读和调试。
不完全确定您的代码有什么问题,如果没有看到完整的代码,很难说清楚。
编辑: 由于您的代码逻辑存在根本性的错误,因此这里有一个完全包含的示例:
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
class product {
public:
product(std::string name, double cost);
~product();
//in product class, add the < operator
bool product::operator< (const product &other) const;
std::string Name;
double Cost;
double Discount;
};
product::product(std::string name, double cost) : Name(name), Cost(cost){}
product::~product(){}
const double highDiscount = 0.3;
const double midDiscount = 0.2;
const double lowDiscount = 0.1;
struct CompareProductPointers {
bool operator()(const product* l, const product* r) {
return *l < *r;
}
};
int main() {
//create a vector holding all your products
product product1("product1", 10);
product product2("product2", 8);
product product3("product3", 12);
std::vector<product*> products;
products.push_back(&product1);
products.push_back(&product2);
products.push_back(&product3);
//sort your product vector (which will sort by cost)
std::sort(products.begin(), products.end(), CompareProductPointers());
//apply your discount to the sorted elements
products[0]->Discount = lowDiscount;
products[1]->Discount = midDiscount;
products[2]->Discount = highDiscount;
//output
std::cout << product1.Name << " has a " << (product1.Discount * 100) << "% discount" << std::endl;
std::cout << product2.Name << " has a" << (product2.Discount * 100) << "% discount" << std::endl;
std::cout << product3.Name << " has a" << (product3.Discount * 100) << "% discount" << std::endl;
return 0;
}