首页 > 解决方案 > 切换语句未按预期工作c#

问题描述

我正在尝试制作一个程序,根据用户的状态以及他们在酒店住宿的天数选择不同的折扣,但我的 switch 语句根本不起作用。我尝试过使用休息来查看它失败的地方,但我没有运气。

private void BtnCompute_Click(object sender, EventArgs e)
{
    //declaring variables
    double ratePerDay, preDiscountCost, totalCost;
    string customerStatus = (txtCustomerStatus.Text);

    //getting input from text boxes
    int days = int.Parse(txtDays.Text);
    ratePerDay = double.Parse(txtRatePerDay.Text);

    //initializing discount variable
    double discount = 0;
    //if statement to tell which discount should be applied if any.
    if (days <= 3)
        switch (customerStatus)
        {
            case "Gold":
                discount = 15 / 100;
                break;
            case "Platinum":
                discount = 20 / 100;
                break;
            default:
                discount = 0;
                break;
        }
    else if (days >= 4)    
        switch (customerStatus)
        {
            case "Gold":
                discount = 25 / 100;
                break;
            case "Platinum":
                discount = 30 / 100;
                break;
            default:
                discount = 0;
                break;
        }
    else
    { 
        discount = 0;
    }

标签: c#if-statementswitch-statement

解决方案


正如@John 所说,您正在黄金和铂金块中执行整数除法。15 / 100是整数除法(因为15int文字并且100int文字)并导致0. 分配到double仅在除法发生后发生。

https://en.wikipedia.org/wiki/Truncation

至少有一个除数必须是 adouble才能获得预期结果。您可以尝试除以15.0 / 100or 15 / 100.0or 15.0 / 100.0or or (double)15 / 100or 15 / (double)100


推荐阅读