我的問題不是關於代碼,因爲它是編寫因子程序的邏輯。我目前正在赫爾辛基大學攻讀MOOC,並且我一直陷在這個練習中。隨着課程開始進行新的練習,說明變得越來越模糊。我意識到這可能不是問這個問題的地方,如果你必須標記或刪除它,我明白。我想自己學習,因爲我沒有時間或金錢去實際上大學。本課程沒有時間限制,我不會獲得成績證書,我只是想要知識。如何編碼因子
這些都爲鍛鍊
創建計算數n的階乘的程序給出的說明。因子n!使用公式1 * 2 * 3 * ... * n計算。例如4! = 1 * 2 * 3 * 4 = 24。另外,它被定義爲0! = 1
// i don't understand the example that 4!= 1*2*3*4 = 24
// or how 0! = 1 pertains to multiplying numbers in succession to find the
// factorial of the user input number.
// i understand that 0! = 1 simply delclares that 0 is not equal to 1
// and 4 is not equal to 24, however if the 4! = portion of this statement
// is in reference to the user input number 4 that statement would not be
// true as 1*2*3*4 does equal 24 and 4 would be the number of executions
// of the block execution of the loop required to write the factorial
// program.
// EDIT: okay so according to this http://en.wikipedia.org/wiki/Factorial
// i am wrong about what is being done here as they are not declaring
// that 4 not equals 24 but yet that 4! is a way of correlating the non
// negative numbers up to 4, but given that math is not my strong suit
// it is even more confusing to me as to what i should be doing.
實施例輸出:
類型的數:3 階乘是6
類型的數:10 階乘是3628800
我當前的代碼的企圖是如下
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
int userIn = Integer.parseInt(reader.nextLine());
int factorial = 1;
int extra = 1;
int sum = 0;
while (factorial <= userIn) {
factorial++;
sum = factorial + userIn + extra;
}
System.out.println("The factorial is:"+sum);
}
}
我沒有看到我知道這是什麼,我錯過了,我從研究知道,在現實世界中,你不會編碼這個,因爲你可以下載庫來執行比我可以編碼更高效的因子函數,但是我不'我不想簡單地跳過這個練習,知道別人已經編碼並創建了一個圖書館來讓我們的生活更輕鬆,我想學習這門課程所提供的一切。如果我做了一個簡單的錯誤,我不介意提供的代碼更正,但是我想了解是什麼使得階乘操作可以這麼說,而不僅僅是給出答案,所以我可以繼續前進。
我認爲你需要做的第一件事就是了解階乘運營商做什麼。一旦你明白了,代碼應該比較容易。維基百科的文章明確指出*真的*清楚。什麼因素混淆了你? – awksp
'4!'的概念只是寫作'4 * 3 * 2 * 1'的一種緊湊方式。而已。任何整數的階乘本身都乘以小於它的每個整數。所以'5' ='5 * 4 * 3 * 2 * 1'同樣,'6!'='6 * 5!' – Kon
定義:'n! = n *(n-1)!; 1! = 1!*(1-1)! => 1! == 0!'所以你應該考慮邊界約束=> factorial(0)== factorial(1)= 1。這就是訣竅;)。那麼如果(n> 1)?階乘(n-1)* n,否則返回1; –