运行此代码时收到NaN
错误。我一直试图找出原因,但不能为我的生活做好准备。
澄清一下,我想收到;
客户欠款总额
输入了多少客户
function Summarise()
{
ID = prompt("Enter a Customer ID number ", -1)
while(ID != -1)
{
var gasUsed = 0
var total = 0
gasUsed = prompt("Enter amount of gas used ", "0")
///Standard Rate is used to assist in the calculation of customers in excess of 60 Gas Used
StandardRate = 60 * 1.75
if(gasUsed <= 60)
{
total= gasUsed * 2
document.write("Customers ID: " + ID)
document.write(" has gas usage of " + gasUsed)
document.write(" and owes $" + total)
document.write("<br/>")
}
else
{
total= (gasUsed - 60) * 1.50 + StandardRate
document.write("Customers ID: " + ID)
document.write(" has gas usage of " + gasUsed)
document.write(" and owes $" + total)
document.write("<br/>")
}
var totalowed = total + totalowed
var totalcustomers = ++totalcustomers
ID = prompt("Enter a Customer ID number ", -1)
}
document.write("Total amount owed $" + totalowed)
document.write("<br/>")
document.write("Total Number of customers:" + totalcustomers)
}
答案 0 :(得分:0)
totalowed和totalcustomers在while循环中声明,因此在其外部不可用。您需要在while循环之外定义它们。
答案 1 :(得分:0)
您需要在循环之前定义这两个变量:
var totalowed = 0;
var totalcustomers = 0;
当你为它们分配值时,它们最初是未定义的,这总是会产生问题。
您可以在下面看到工作代码段:
function Summarise() {
ID = prompt("Enter a Customer ID number ", -1)
var totalowed = 0;
var totalcustomers = 0;
while(ID != -1)
{
var gasUsed = 0;
var total = 0;
gasUsed = prompt("Enter amount of gas used ", "0");
///Standard Rate is used to assist in the calculation of customers in excess of 60 Gas Used
StandardRate = 60 * 1.75
if(gasUsed <= 60)
{
total = gasUsed * 2;
document.write("Customers ID: " + ID);
document.write(" has gas usage of " + gasUsed);
document.write(" and owes $" + total);
document.write("<br/>");
}
else
{
total= (gasUsed - 60) * 1.50 + StandardRate;
document.write("Customers ID: " + ID);
document.write(" has gas usage of " + gasUsed);
document.write(" and owes $" + total);
document.write("<br/>");
}
totalowed = total + totalowed;
totalcustomers = ++totalcustomers;
ID = prompt("Enter a Customer ID number ", -1);
}
document.write("Total amount owed $" + totalowed);
document.write("<br/>")
document.write("Total Number of customers:" + totalcustomers);
}
Summarise();
答案 2 :(得分:-1)
您没有将提示符中的字符串转换为整数。见这里:
您可以使用:
ID = parseInt(prompt("Enter a Customer ID number ", -1), 10);
请记住为parseInt
函数提供基数值以确保完整性。