スティーブと彼の家族は5つの異なるレストランに行きました。請求書は、124ドル、48ドル、268ドル、180ドル、42ドルでした。スティーブは、請求額が50ドル未満の場合は20%、50ドルから200ドルの場合は15%、200ドルを超える場合は10%をチップします。このプログラムをJavaScriptで作成していますが、配列に個別の値を格納できません。その方法を教えてください。
これはコードです
let bill = [48, 42, 124, 180, 268];
let x, tip1, tip2, tip3, total1, total2, total3;
let tip;
let total;
class Tip {
TipCalc() {
for (x of bill) {
if (x < 50) {
tip1 = x * 0.20;
total1 = x + tip1;
}
if (x >= 50 && x < 200) {
tip2 = x * 0.15;
total2 = x + tip2;
}
if (x >= 200) {
tip3 = x * 0.10;
total3 = x + tip3;
}
tip = [tip1, tip2, tip3];
total = [total1, total2, total3];
}
console.log('tip array ' + tip);
console.log('total array ' + total);
}
}
let t1 = new Tip();
t1.TipCalc();
次のように、値を配列に格納できます。
let bill = [48, 42, 124, 180, 268];
let x;
let tipValue, tip;
let tips = [], totals = [];
class Tip {
TipCalc() {
for (x of bill) {
if (x < 50) {
tipValue = 0.2;
} else if (x >= 50 && x < 200) {
tipValue = 0.15;
}else if (x >= 200) {
tipValue = 0.1;
}
tip = (x * 100 * tipValue) / 100;
tips.push(tip);
totals.push(x + tip);
}
console.log('tip array ' + tips);
console.log('total array ' + totals);
}
}
let t1 = new Tip();
t1.TipCalc();
丸め誤差を避けるために乗算は整数で行われることに注意してください。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加