【发布时间】:2015-06-18 18:10:17
【问题描述】:
我在 for 循环中有一个嵌套的 if/else 语句来确定一个值是否对数组值有效。它返回所有值都很好,但是如果 IF 是正确的,它仍然会执行 else 额外的 3 次。我以为一旦相等,它就会停止,但我想我在这里遗漏了一些东西。
string sectionChoice;
int ticketQuantity;
double ticketPrice, totalCost;
string[] section = { "orchestra", "mezzanine", "balcony", "general" };
double[] price = { 125.25, 62.00, 35.75, 55.50 };
bool isValidSection = false;
sectionChoice = GetSection();
ticketQuantity = GetQuantity();
for (int x = 0; x < section.Length; ++x)
{
if (sectionChoice == section[x])
{
isValidSection = true;
ticketPrice = price[x];
totalCost = CalcTicketCost(ticketPrice, ticketQuantity);
Console.Write("\n\nTotal cost for the tickets are: {0:c2}", totalCost);
}
else
Console.Write("\n\nInvalid entry, {0} does not exist", sectionChoice);
}
当它有效时,它返回如下内容:
您的价格是 32.50。无效条目,x 不存在 无效条目,x 不存在 无效条目,x 不存在
【问题讨论】:
-
您应该使用
decimal来表示货币值 (read more)。
标签: c# if-statement for-loop