这是我的任务,所以很清楚我想做什么。
编写一个程序,根据三个因素计算酒店房间的价格。首先,一个房间里有多少人: 1-2,3-4,还是5-6?一间房不允许超过六人。第二,客人是AAA的会员吗?第三,他们想要有风景的房间吗?这一比率计算如下: 基本房价是:1至2人=50美元/晚,3-4人=60美元/晚,5-6人=70美元/晚。AAA会员可享受每晚基本房价的折扣: 1-2人= 15%,3-4人= 10%,5-6人= 5%。 该程序应提示用户提供所有输入,执行计算,并输出每晚的总成本。建议至少使用一些嵌套的if/else结构来计算成本。
像firebug和JSLint这样的调试器没有任何帮助,我怀疑我只是做了一些完全错误的事情,尽管我以前没有遇到过“嵌套if”逻辑分配的问题。不管我是个彻头彻尾的纽比。
当我通过为numberOfGuests输入1、为tripleAStatus输入N和输入roomView输入N进行测试时,finalRate返回为isNaN (我知道这意味着不是数字),但我不知道原因。
//Variable Declaration
var numberOfPeople;
var tripleAStatus;
var roomView;
var discountRate;
var roomRate;
var finalRate;
var discountPercent;
//Input
numberOfPeople = prompt("How many guests will their be? 6 Maximum.");
tripleAStatus = prompt("Are you a AAA Member? Y/N.");
roomView = prompt("Would you like your room to have a view?");
//Logic
if ((numberOfPeople <= 2) && (numberOfPeople > 0)) {
roomRate = 50;
discountPercent = .15;
} else if ((numberOfPeople <= 4) && (numberOfPeople > 2)) {
roomRate = 60;
discountPercent = .10;
} else if ((numberOfPeople <= 5) && (numberOfPeople > 4)) {
roomRate = 70;
discountPercent = .5;
} else {
alert("Your number of guests must be at least 1 and no more than 6");
}
if (tripleAStatus = "Y") {
discountRate = roomRate - (roomRate * discountRate);
} else if (tripleAStatus = "N") {
discountRate = roomRate;
} else {
alert("You need to answer with either Y or N");
}
if (roomView = "Y") {
finalRate = (discountRate) + ((discountRate) * .10);
} else if (roomView = "N") {
finalRate = discountRate;
} else {
alert("You need to answer with either Y or N");
}
//Output
document.write("Total cost per night is " + "$" + finalRate);发布于 2012-10-17 23:49:29
看起来像是
discountRate = roomRate - (roomRate * discountRate);应改为
discountRate = roomRate - (roomRate * discountPercent);这就是为什么您要在finalRate中获得discountRate;此时还没有定义discountRate,因此您的代码实际上读取了discountRate = 1 - (1 * undefined)。
正如其他海报所提到的,您还需要更改条件以使用==或===;=是赋值运算符,所以与其检查tripleAStatus是否为"Y",不如实际检查"Y"是否为true (它总是这样)。
tripleAStatus = 'N';
if (tripleAStatus = 'Y') {
// tripleAStatus is now "Y", and the code inside this if will always be executed
}工作更改:http://jsfiddle.net/5ZVkE/
发布于 2012-10-17 23:48:06
在If语句中,使用单个"=“赋值。由于赋值总是发生,它将返回true。为了比较值,需要在if语句中使用双重"==“。就像这样:
if (tripleAStatus == "Y") {
discountRate = roomRate - (roomRate * discountRate);
} else if (tripleAStatus == "N") {
discountRate = roomRate;
} else {
alert("You need to answer with either Y or N");
}发布于 2012-10-17 23:48:22
将“if”语句中的“=”替换为“=”。您目前使用的是赋值运算符而不是相等。
例如:
if (tripleAStatus == "Y") ...https://stackoverflow.com/questions/12945086
复制相似问题