2014-11-16 2 views
0

Чтобы быть более конкретным, я пытаюсь сделать программу для расчета цены. Цена должна изменить, чем больше вы покупаете.Как установить переменную, которая изменяется в соответствии с другой переменной

<html xmlns="http://www.w3.org/1999/xhtml" lang="en"> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>Transaction Invoice</title> 
    <meta name="author" content="Caprica" /> 
    <!-- Date: 2014-11-12 --> 
</head> 
<body> 
<script type="text/javascript"> 
// Program name: Transaction Invoice 
// Purpose: To do a transaction 
// Author: Ephraim Vickers 
// Date last modified: Today 

// Variables 
var BREAK = "<br />" 
var pricePound = 1.13;   // This is the price per pound 
var amountPurchased = 0;   // Number of pounds purchased 
var reducRate = parseInt (document.getElementById ("0.02").value);    // This is the percent it is reduced 
var noDiscount = pricePound * amountPurchased;  //Cost without discount 
var reducCost = noDiscount - amountSaved; 
var amountSaved = noDiscount * reducRate; 
document.write ("Hello and thank you for shopping at the ACME cement company. This program is here to handle transaction information and apply discounts. For all other concerns please go to our main site." + BREAK) 
window.alert("Please be aware that all cement purchases are on sell and, the more you buy the more it will be discounted!!! All numbers inputted will be converted to pounds. Some restrictions and limitations do apply see a instore clerk for details.") 
amountPurchased = prompt ("Valued customer, please enter the amount of cement you would like to purchase."); 
noDiscount = pricePound * amountPurchased 
reducCost = noDiscount - amountSaved 
amountSaved = noDiscount * reducRate 
parseFloat(reducRate) 

if (amountPurchased <= 0) { 
    window.alert("ERROR. Your purchase is below our minimum purchase amount. Please refresh the page and increase the amount you are trying to purchase."); 
} 
if (amountPurchased <= 500) { 
    reduceRate = 0.02; 
} 
if (amountPurchased <=9000) { 
    reduceRate = 0.04; 
} 
if (amountPurchased <= 15000) { 
    reduceRate = 0.05; 
} 
if (amountPurchased >= 15000) { 
    reduceRate = 0.09; 
}; 
document.write (amountSaved); // This also returns 0 but i think its because of the reducRate 
document.write (reducRate); //This is the part that always returns 0 
</script> 

По какой-то причине lowerRate продолжает возвращать ноль. Как сделать изменение ставки с суммой. Извините, что не разместили все это

+2

Мы должны видеть весь код. –

+0

- глобальная переменная reduceRate? если вы не знаете /, чтобы убедиться, что замените его на window.reduceRate – TakeMeAsAGuest

+2

Из этого кода, если 'amountPurchased' меньше, чем' 14,999', он всегда будет возвращать 'lowerRate' в' 0.05'. –

ответ

1

Проблема очень проста: вы видите ваше имя переменной неправильно. Просто измените reducRate на reduceRate (против 2-й е в Reduc е Rate), и все должно работать нормально ...

Кроме того, что вы также должны действительно использовать else if вместо if.

Так что ваш код будет выглядеть следующим образом:

<html xmlns="http://www.w3.org/1999/xhtml" lang="en"> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>Transaction Invoice</title> 
    <meta name="author" content="Caprica" /> 
    <!-- Date: 2014-11-12 --> 
</head> 
<body> 
<script type="text/javascript"> 
// Program name: Transaction Invoice 
// Purpose: To do a transaction 
// Author: Ephraim Vickers 
// Date last modified: Today 

// Variables 
var BREAK = "<br />" 
var pricePound = 1.13;   // This is the price per pound 
var amountPurchased = 0;   // Number of pounds purchased 
var reduceRate = parseInt (document.getElementById ("0.02").value);    // This is the percent it is reduced 
var noDiscount = pricePound * amountPurchased;  //Cost without discount 
var reducCost = noDiscount - amountSaved; 
var amountSaved = noDiscount * reduceRate; 
document.write ("Hello and thank you for shopping at the ACME cement company. This program is here to handle transaction information and apply discounts. For all other concerns please go to our main site." + BREAK) 
window.alert("Please be aware that all cement purchases are on sell and, the more you buy the more it will be discounted!!! All numbers inputted will be converted to pounds. Some restrictions and limitations do apply see a instore clerk for details.") 
amountPurchased = parseFloat(prompt ("Valued customer, please enter the amount of cement you would like to purchase.")); 
noDiscount = pricePound * amountPurchased; 
reducCost = noDiscount - amountSaved; 
amountSaved = noDiscount * reduceRate; 

if (amountPurchased <= 0) { 
    window.alert("ERROR. Your purchase is below our minimum purchase amount. Please refresh the page and increase the amount you are trying to purchase."); 
} else if (amountPurchased <= 500) { 
    reduceRate = 0.02; 
} else if (amountPurchased <= 9000) { 
    reduceRate = 0.04; 
} else if (amountPurchased <= 15000) { 
    reduceRate = 0.05; 
} else { //only occurs when none of the others are true: so this is when it's >15000 
    reduceRate = 0.09; 
} 
document.write (amountSaved); // This also returns 0 but i think its because of the reducRate 
document.write (reduceRate); //This is the part that always returns 0 
</script> 
+0

Спасибо SOOOOOO Much –

+0

@RedVickers Я сделал несколько изменений: вы всегда должны 'parseFloat()' любой текстовый ввод, который вы получаете через 'prompt()', и обычно лучше всего положить точки с запятой в конце строк (просто как хорошая привычка). – Joeytje50

+0

он видит, что проблема с amountSaved не вычитается из noDiscount. Я не вижу причины, почему –

2

В некоторых местах вы указываете reducRate и reduceRate в других местах. Измените все ссылки от reducRate на reduceRate.

Кроме того, ваши статусы, если вы делаете неверные данные для получения ставки. Вы должны использовать else if условия, чтобы исправить это:

function getRate(amountPurchased) { 
    if (amountPurchased <= 500) { 
     return 0.02; 
    } 
    else if (amountPurchased <=9000) { 
     return 0.04; 
    } 
    else if (amountPurchased <= 15000) { 
     return 0.05; 
    } 
    else { // amountPurchased > 15000 
     return 0.09; 
    } 
} 

console.log(getRate(0) == 0.02); 
console.log(getRate(500) == 0.02); 
console.log(getRate(501) == 0.04); 
console.log(getRate(9000) == 0.04); 
console.log(getRate(9001) == 0.05); 
console.log(getRate(15000) == 0.05); 
console.log(getRate(15001) == 0.09); 

И вы должны разобрать amountPurchased как поплавок. Сейчас это строка:

amountPurchased = parseFloat(prompt("Valued customer, please enter the amount of cement you would like to purchase.")); 

Кстати, два из ваших условий будет возвращать верно для 15000:

if (amountPurchased <= 15000) 
if (amountPurchased >= 15000) 
+0

+1 только для *' if'/'else if' * ... –

+0

О, извините, мое подключение к Интернету ДЕЙСТВИТЕЛЬНО плохо, так что я сделал Я вижу ваш ответ, размещенный здесь, когда я начал печатать мой. В противном случае я бы не опубликовал его. +1 в любом случае для определения проблемы. PS: у вас есть одна опечатка: вы скажете, что «вернется true для 1500», которая должна быть «... за 1500 ** 0 **» – Joeytje50

+0

@ Joeytje50 +1 вам ответят на это в их контексте. Я уже написал большую часть своего ответа, прежде чем отредактировать этот вопрос со всем кодом. Кроме того, спасибо, что заметили 1500. Я потерялся в нулях. –

Смежные вопросы