我是javascript的新手,所以我可能犯了一个非常简单的错误,但基本上它是什么,我试图在javascript中制作一个小的价格计算器,它的工作但问题是它返回的数字是荒谬的高。
我已经做了很多搜索,我找不到答案,我已经尝试避免浮动数字和我现在正在做的分裂,因为它让我更接近我认为正确的数字。我已经尝试在我的更多代码上使用.toFixed,看看是否有任何导致我的失败,但没有运气。就像现在如果你尝试用彩色300张名片,单面它可能会说它是“£100.0614.29”我得到这个更低的唯一方法是添加一个愚蠢的数量更多的零
var click = (amount / 3) / 1000;
if (color === "color") {
click = (amount / 5) / 1000;
};
这里。
但这只会降低到1000以上,如果我删除点击费用,它仍然是1000 ish。
修改
我正在寻找更多解释为什么我得到这些结果并帮助得到答案,让它像我认为的那样工作。给我足够的时间和睡眠,我想我可以解决这个问题,我只是不明白为什么会发生这种情况。
答案 0 :(得分:2)
算术运算中类型的转换按运算执行的顺序完成。在表达式中,所有内容都将转换为连接的字符串。
var rip = 11;
var click = 22;
var type = 33.44;
return "£" + rip + click + type.toFixed(2);
= "£112233.44"
return "£" + (rip + click + type).toFixed(2);
= "£66.44"
答案 1 :(得分:0)
嗨,你的代码有点改变了。 首先,当你划分""的数量时,我已经添加了一张支票。让我们说你可以适应4"工作"在一个页面上 - 然后当订单是7"工作"你需要计算两页而不是一页(就像在你的剧本中一样)
但最后你需要做的就是设定价格(适用于B& W页面)和priceColor(适用于彩色)
var type = prompt("What type of job is it?").toLowerCase();
console.log(type);
var amount = prompt("how many would you like?");
console.log(parseInt(amount));
if (type === "business cards" || type === "bus cards" || type === "bus card") {
amount = (amount % 21) > 0? (amount / 21)+1 : amount / 21;
console.log(parseInt(amount));
} else if (type === "leaflets" || type === "Flyers" || type === "a5") {
amount = (amount % 4) > 0? (amount / 4)+1 : amount / 4;
console.log(parseInt(amount));
} else if (type === "letterheads" || type === "a4") {
amount = (amount % 2) > 0? (amount / 2)+1 : amount / 2;
console.log(parseInt(amount));
};
var color = prompt("Black and white or color?").toLowerCase();
console.log(color);
var side = prompt("Is it single or double sided?").toLowerCase();
console.log(side);
var price = 10;
var priceColor = 15;
if (side == "double sided") {
price = price * 2;
priceColor = priceColor * 2;
};
if (color === "color") {
price = priceColor;
};
function add() {
return "£" +(price*amount);
};
console.log(add())

希望这有帮助。