C# 试图通过避免使用if、else、if-else和switch语句来修复数组边界之外的问题,因为我只能使用user if一次

C# 试图通过避免使用if、else、if-else和switch语句来修复数组边界之外的问题,因为我只能使用user if一次,c#,C#,如何使quantityPurchased大于或等于200时,不使用if、if-else、else或switch语句,它不会超出数组的界限 static double DeterminePercentage(int quantityPurchased) { double[] quantity = { 1, 11, 50, 100, 200 }; double[] discount = { 0, 7.5, 15, 17.5, 20 }; int x = 0; for

如何使quantityPurchased大于或等于200时,不使用if、if-else、else或switch语句,它不会超出数组的界限

static double DeterminePercentage(int quantityPurchased)
{
    double[] quantity = { 1, 11, 50, 100, 200 };
    double[] discount = { 0, 7.5, 15, 17.5, 20 };
    int x = 0;
    for (int i = 0; i < quantity.Length; i++)
    {
        if (quantityPurchased >= quantity[i] && quantityPurchased < quantity[i + 1])
        {
            x = i;
        }
        break;
    }

    return discount[x];
}
static double determinatePercentage(已购买int quantityPurchased)
{
双[]数量={1,11,50,100,200};
双[]折扣={0,7.5,15,17.5,20};
int x=0;
for(int i=0;i=数量[i]&数量采购<数量[i+1])
{
x=i;
}
打破
}
退货折扣[x];
}

只需少循环一项:

for (int i = 0; i < quantity.Length - 1; i++) {

这将使数量介于200和Int32之间。MaxValue有20%的折扣。

如果“数量”数组增长并且仍然排序,最佳和通用的答案是使用二进制搜索值“quantityPurchased”。它将为您提供插入点,即将密钥插入阵列的点。 使用此索引从折扣数组返回适当的值

我不提供代码,因为我不是C#用户,但实现应该不会很复杂


干杯。

在数量数组末尾添加Double.MAX\u值:

double[] quantity = { 1, 11, 50, 100, 200, Double.MAX_VALUE };

试试这个Linq表达式


退货折扣[折扣.IndexOf(quantity.Where(x=>x>quantityPurchased).DefaultIfEmpty().Max());

对不起,我想我没有澄清。如果我有这样的折扣(int I=0;Iif一次?
double[] quantity = { 1, 11, 50, 100, 200, Double.MAX_VALUE };