開始我的編碼學習之路,但我遇到了一個小問題。我正在嘗試撰寫一個代表以下內容的程式;
// Write a program that prints a message to the screen based on a users age and country.
// Feel free to change these variables or create new ones so you can test all cases.
const age = 20
const country = 'USA'
// if the user is younger than 16 print "You're not old enough to do anything yet."
// if the user is at least 16 but not yet 18 print "Be careful driving."
// if the user is 18 but not yet 21 and the user lives in the USA pring "Go Vote!"
// if the user is at least 18 but younger than 21 and lives outside of the US print "You can probably have some wine."
// In all other cases print "You're old enough to figure it out for yourself."
到目前為止,我得到了這個:
const age = 20
const country = "USA"
const otherCountry = "Other country"
console.log(age)
console.log(otherCountry)
if (age < 16 ) {
console.log("You're not old enough to do anything.")
}
else if (age >=16 && age <=18) {
console.log ("Be careful driving")
}
else if (age >=18 && age <=21 && country) {
console.log("Go Vote!")
}
else if (age >=18 && age <=21 && otherCountry){
console.log ("You can prbably have some wine")
}
else
{console.log ("You're old enough to figure it out")
}
我似乎無法弄清楚如何在“else if”陳述句中表達國家。菜鳥必須從某個地方開始。提前致謝
uj5u.com熱心網友回復:
你的邏輯有問題。
首先尚未 18可能意味著< 18而不是<= 18。(21 相同)
其次,一旦你進入你的"Go vote"分支,你就不能再進入這個"Wine"分支,因為一旦遇到一個if .. else if .. else條件,就不會再評估其他條件了。
因此,如果您有一個 18 至 21 歲的人,您必須檢查該分支機構的附加條件(即居住在美國或任何其他國家/地區)。
let age = 19;
let livesin = "USA";
if (age < 16 ) {
console.log("You're not old enough to do anything.")
}
//you don't need >=16 here, because as the first condition failed
//we alread know that age >= 16
else if (age < 18) {
console.log ("Be careful driving")
}
//you don't need >=18 here, because as the first and second condition failed
//we already know that age >= 18
else if (age <21) {
//for people between 18 and 21, check if they live in the USA or not
if (livesin === "USA") console.log("go vote");
else console.log("You can prbably have some wine")
}
else {
console.log ("You're old enough to figure it out")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/314892.html
標籤:javascript
