亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

更新后的帖子:如何獲得 JavaScript 階乘程序的循環來顯示所使用的工作?查看要求

更新后的帖子:如何獲得 JavaScript 階乘程序的循環來顯示所使用的工作?查看要求

喵喵時光機 2023-08-18 14:09:20
我面臨的挑戰是用 JavaScript 編寫一個程序,允許用戶執行多項任務,其中之一是要求用戶提供一個數字并計算該數字的階乘,然后以需求中列出的格式顯示它。由于我對 Java 腳本了解不多,所以我使用了已經提出的問題并設法使計算正常工作,但無法弄清楚如何在仍滿足要求的情況下獲得所需的輸出。要求: &bull; 只能使用提供的變量 Number(初始化為 0 的變量,用于保存用戶輸入) Factorial(初始化為 1 的變量,用于保存計算的階乘值) Count(用于保存執行階乘計算的循環次數的變量)。這是挑戰設置的限制,而不是我的限制。 &bull; 無法使用精美的庫。 &bull; 需要對輸出使用循環解決方案。另一篇文章的答案需要引入新的變量,也許是我缺乏理解,但也許自上一篇文章以來我獲得的寫得不好的偽代碼可能會有所幫助。&bull; 以以下格式輸出:(這是一個警報,因此程序的一部分沒問題)The factorial of 5 is 5*4*3*2*1=120?OR5! is? 5*4*3*2*1=120?偽代碼寫得不好:代碼://prompts the user for a positive numbervar number = parseInt(prompt("Please enter a positive number"));console.log(number);//checks the number to see if it is a stringif (isNaN(number)){? alert("Invalid. Please Enter valid NUMBER")}//checks the number to see if it is negaiveelse if (number < 0)?{? alert("Please Enter valid positive number");}//if a positive integer is entered a loop is started to calculate the factorial of the number the user enteredelse {? ? let factorial = 1;? ? for (count = 1; count <= number; count++) {? ? ? ? factorial *= count;? ? ? ? ?}? ??? ? //Sends the inital number back to the user and tells them the factorial of that number? ? alert("The factorial of " + number + " is " + factorial + ".");}
查看完整描述

1 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

number這是一個有點骯臟的黑客,但它應該滿足除了、count、 和 之外不factorial使用其他變量的條件。


let number = 5;

let factorial = 120; 

// ^ Do your own calculation for this


alert(`The factorial of ${number} is ${Array.from(Array(number + 1).keys()).slice(1).reverse().join("*")}=${factorial}`)

那么這是怎么回事呢?我們使用插值模板字符串來生成所需的輸出,其中的表達式${these things}被評估為字符串。我們在那里放了什么亂七八糟的東西?


Array.from(Array(number + 1).keys())


上面的表達式創建了數組[0,1,2,3,4,5]。


.slice(1)給我們[1,2,3,4,5]


.reverse()給我們[5,4,3,2,1]


join("*")給我們"5*4*3*2*1"


當所有這些放在一起時,我們得到了The factorial of 5 is 5*4*3*2*1=120


瞧!輸出以所需的格式打印,而不引入任何新變量。


編輯:哦,您不需要為此使用內插字符串。您也可以像在問題中所做的那樣將常規字符串連接在一起。例如


 "The factorial of " + factorial + " is " + Array.from(Array(number + 1).keys()).slice(1).reverse().join("*") + "=" + factorial


查看完整回答
反對 回復 2023-08-18
  • 1 回答
  • 0 關注
  • 84 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號