c# - 切换语句未按预期工作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;
}
解决方案
正如@John 所说,您正在黄金和铂金块中执行整数除法。15 / 100
是整数除法(因为15
是int
文字并且100
是int
文字)并导致0
. 分配到double
仅在除法发生后发生。
https://en.wikipedia.org/wiki/Truncation
至少有一个除数必须是 adouble
才能获得预期结果。您可以尝试除以15.0 / 100
or 15 / 100.0
or 15.0 / 100.0
or or (double)15 / 100
or 15 / (double)100
。
推荐阅读
- java - 启动错误 - 原因:java.lang.NullPointerException
- c# - 如何在 EF Core 3.1.3 中禁用延迟加载?
- verilog - Modelsim:错误:(vsim-3033)...“MUT”的实例化失败。未找到设计单位
- javascript - Angular javascript页面编译但显示空白
- swift - 已发布值上的 SwiftUI toggle() 函数停止使用 Swift 5.2 触发 didSet
- python - 如何在 python(openCV) 中增加文件名
- go - 当struct实现接口时,“不能在赋值中使用x([struct]类型的变量)作为[interface]值”
- javascript - 通过拖动和滚动循环菜单项
- python-3.x - 如何使用 Selenium 和 Python 从 .aspx 网站上抓取数据
- mysql - 无法通过 SQL Workbench 上的 Putty 连接到远程数据库