亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
如何執(zhí)行Java程式?
使用各種方法的階乘範(fàn)例
範(fàn)例 1 – 使用基本方法
範(fàn)例 2 – 使用使用者輸入
範(fàn)例 3 – 使用遞歸方法
缺點
Example 4 – Using built-in Function
Conclusion –?Factorial in Java
首頁 Java java教程 Java 中的階乘

Java 中的階乘

Aug 30, 2024 pm 04:25 PM
java

在本文中,我們將了解使用 Java 程式語言編寫用於階乘計算的程式碼的各種方法。作為一種易於使用的物件導(dǎo)向語言,Java 是一種獨(dú)立於平臺的簡單程式語言。 Java 的編譯器和解釋器是以安全性為主要方面開發(fā)的。 Java 的應(yīng)用範(fàn)圍非常廣泛。

廣告 該類別中的熱門課程 JAVA 掌握 - 專業(yè)化 | 78 課程系列 | 15 次模擬測驗

開始您的免費(fèi)軟體開發(fā)課程

網(wǎng)頁開發(fā)、程式語言、軟體測試及其他

階乘,符號為“!” (感嘆號),是將一個數(shù)字與所有較小的數(shù)字相乘的數(shù)學(xué)運(yùn)算。例如,如果數(shù)字是 5,階乘的輸出將為 5! = 5*4*3*2*1 = 120.

如何執(zhí)行Java程式?

1.完成您的程式碼並將其另存為 (檔案名稱).java

2.開啟終端機(jī)並執(zhí)行以下 java 指令。

  • a. javac(檔名).java

3.上面的指令將產(chǎn)生一個類別檔案。

4.現(xiàn)在,執(zhí)行類別檔案。

  • a. java(檔名)

使用各種方法的階乘範(fàn)例

以下是使用不同方法的不同範(fàn)例:

範(fàn)例 1 – 使用基本方法

接下來,我們將編寫一個簡單的階乘計算的 Java 程式。

public class Factorial
{
public static void main(String args[])
{int i, fact=1;
int number=5;
for(i=1;i<=number;i++)
{
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}

使用任意檔名和 .java 副檔名儲存上述程式碼。

代碼說明:

它從兩個變數(shù)「i」和「fact」開始,值為 1,然後「number」為 5,這是我們計算階乘的數(shù)字。我進(jìn)入For循環(huán),不斷增加i的值,直到我們將它與一個數(shù)字匹配,即5。在增加的同時,每次fact的值增加,它都會相乘,並且fact被分配一個新值。

輸出:

Java 中的階乘

範(fàn)例 2 – 使用使用者輸入

另一種常用的方法是我們要求使用者輸入數(shù)字進(jìn)行計算,而不是預(yù)先定義它。

參考以下程式碼進(jìn)行基於使用者輸入的計算:

import java.util.Scanner;
class Facto{
public static void main(String args[]) {
int q, a, fact = 1;
System.out.println("Please Enter a number:");
Scanner in = new Scanner(System.in);
q = in.nextInt();
if ( q < 0 )
System.out.println("Please enter a number greater than 0:");
else {
for ( a = 1 ; a <= q ; a++ )
fact = fact*a;
System.out.println("Factorial of "+q+" is = "+fact);
}
}
}

像前面的範(fàn)例一樣保存上面的程式碼。

代碼說明:

前面的範(fàn)例和上面的範(fàn)例之間的主要區(qū)別在於使用者輸入;休息也是一樣。程式碼會要求計算一個數(shù)字,那麼如果使用者輸入的數(shù)字是負(fù)數(shù),即“-”中的減號,則會提示“請輸入大於0的數(shù)字:”,這很明顯,因為階乘不能計算計算為負(fù)數(shù)?,F(xiàn)在,它將接受正數(shù)並繼續(xù)計算階乘,然後列印輸出,如下圖所示。

輸出:

Java 中的階乘

範(fàn)例 3 – 使用遞歸方法

遞歸是程式設(shè)計世界中最有用的工具之一。遞歸基本上意味著重複使用函數(shù)。也就是說,我們不必在這裡定義額外數(shù)量的變量,這意味著我們只有兩個或更少的變數(shù)。

實現(xiàn)遞歸的一個主要原因是能夠減少程式碼長度並優(yōu)雅地降低程式的時間複雜度。遞歸方法雖然有其優(yōu)點,但也有一些缺點,從長遠(yuǎn)來看,這些缺點可能會產(chǎn)生重大影響。

缺點

遞迴的缺點:

  • 基本上,偵錯遞歸程式碼並追蹤它是否有錯誤的步驟是相當(dāng)困難的。
  • 除此之外,遞歸會使用更多內(nèi)存,因為它使用堆疊來完成任務(wù),並透過更新的遞歸呼叫不斷累積堆疊。
  • 而且,如果實作不明智,遞歸會減慢函數(shù)的速度。
  • StackOverflowException:遞歸方法經(jīng)常由於堆疊的過度使用而拋出此異常。

參考以下程式碼:

public class FactorialExample2 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}
}

像我們之前那樣儲存並編譯程式。

代碼說明:

The above code starts with a single int variable and checks if it is equal to 1; if yes, it returns one, as factorial for 1 is 1. If not equal to 1, it proceeds with the recursion function. Our int value, for example, is 5, so it’ll be like “5 * factorial(5-1)”, factorial is called here for the second time, which is another call. Then it returns again with a newer int value, which is 4, “4 * factorial(4-1)”, now it’ll be the third call to the recursion method. Now, the newer int value is 3, which means “3 * factorial(3-1)”, now it’ll be the fourth call, and the value will be 2, which means “2 * factorial(2-1)”. The int value will be one in the next recursive call, which will terminate the function here. While every call was made, its value was saved in a Stack, which is a LIFO method. So, for the final Output, the result will be “5*4*3*2*1 = 120.”

Compared to other methods, Recursion is quite difficult to understand and to implement, but if understood well and implemented wisely, it is a good tool.

Output:

Java 中的階乘

It is highly recommended to use Recursion only in the case where writing an iterative code can be quite complex.

Now that we have learned various methods for implementing Factorial Calculations in Java Let’s explore a Built-in function that does the same work in a single line.

Example 4 – Using built-in Function

*) IntMath

Understanding the need for arithmetic operations over a value, a few functions specific to certain value types were written, we will see the Integer type value in work.

IntMath is a class for arithmetic calculations on an int value. IntMath class comes with a range of arithmetic operations, including factorial.

Syntax:

factorial (int n)

Conclusion –?Factorial in Java

We started with an introduction to java and how to run a java program. Then we learned about Factorial Calculation and various methods, including Recursion, to accomplish it.

Towards the end, we learned about IntMath; a Java Function primarily focused on Arithmetic operations. Java is a widely-used programming language; it comes with many features; in this article, we learned about Factorial Calculations in Java, which is a tiny aspect.

以上是Java 中的階乘的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Laravel Raw SQL查詢示例 Laravel Raw SQL查詢示例 Jul 29, 2025 am 02:59 AM

Laravel支持使用原生SQL查詢,但應(yīng)優(yōu)先使用參數(shù)綁定以確保安全;1.使用DB::select()執(zhí)行帶參數(shù)綁定的SELECT查詢,防止SQL注入;2.使用DB::update()執(zhí)行UPDATE操作並返回影響行數(shù);3.使用DB::insert()插入數(shù)據(jù);4.使用DB::delete()刪除數(shù)據(jù);5.使用DB::statement()執(zhí)行如CREATE、ALTER等無結(jié)果集的SQL語句;6.推薦在QueryBuilder中使用whereRaw、selectRaw等方法結(jié)合原生表達(dá)式以提升安

使用Junit 5和Mockito在Java進(jìn)行單位測試和嘲笑 使用Junit 5和Mockito在Java進(jìn)行單位測試和嘲笑 Jul 29, 2025 am 01:20 AM

使用JUnit5和Mockito能有效隔離依賴進(jìn)行單元測試,1.通過@Mock創(chuàng)建模擬對象,@InjectMocks注入被測實例,@ExtendWith啟用Mockito擴(kuò)展;2.使用when().thenReturn()定義模擬行為,verify()驗證方法調(diào)用次數(shù)與參數(shù);3.可模擬異常場景並驗證錯誤處理;4.推薦構(gòu)造函數(shù)注入、避免過度模擬、保持測試原子性;5.使用assertAll()合併斷言,@Nested組織測試場景,從而提升測試可維護(hù)性和可靠性。

以身作則 以身作則 Jul 29, 2025 am 04:10 AM

Go泛型從1.18開始支持,用於編寫類型安全的通用代碼。 1.泛型函數(shù)PrintSlice[Tany](s[]T)可打印任意類型切片,如[]int或[]string。 2.通過類型約束Number限制T為int、float等數(shù)字類型,實現(xiàn)Sum[TNumber](slice[]T)T安全求和。 3.泛型結(jié)構(gòu)體typeBox[Tany]struct{ValueT}可封裝任意類型值,配合NewBox[Tany](vT)*Box[T]構(gòu)造函數(shù)使用。 4.為Box[T]添加Set(vT)和Get()T方法,無需

CSS桌面固定示例 CSS桌面固定示例 Jul 29, 2025 am 04:28 AM

table-layout:fixed會強(qiáng)製表格列寬由第一行單元格寬度決定,避免內(nèi)容影響佈局。 1.設(shè)置table-layout:fixed並指定表格寬度;2.為第一行th/td設(shè)置具體列寬比例;3.配合white-space:nowrap、overflow:hidden和text-overflow:ellipsis控製文本溢出;4.適用於後臺管理、數(shù)據(jù)報表等需穩(wěn)定佈局和高性能渲染的場景,能有效防止佈局抖動並提升渲染效率。

Python JSON負(fù)載示例 Python JSON負(fù)載示例 Jul 29, 2025 am 03:23 AM

json.loads()用於將JSON字符串解析為Python數(shù)據(jù)結(jié)構(gòu),1.輸入必須是雙引號包裹的字符串且布爾值為true/false;2.支持null→None、對象→dict、數(shù)組→list等自動轉(zhuǎn)換;3.常用於處理API返回的JSON字符串,如response_string經(jīng)json.loads()解析後可直接訪問嵌套數(shù)據(jù),使用時需確保JSON格式正確,否則會拋出異常。

MongoDB的索引策略 MongoDB的索引策略 Jul 29, 2025 am 01:05 AM

Choosetheappropriateindextypebasedonusecase,suchassinglefield,compound,multikey,text,geospatial,orTTLindexes.2.ApplytheESRrulewhencreatingcompoundindexesbyorderingfieldsasequality,sort,thenrange.3.Designindexestosupportcoveredqueriesbyincludingallque

Java項目管理Maven的開發(fā)人員指南 Java項目管理Maven的開發(fā)人員指南 Jul 30, 2025 am 02:41 AM

Maven是Java項目管理和構(gòu)建的標(biāo)準(zhǔn)工具,答案在於它通過pom.xml實現(xiàn)項目結(jié)構(gòu)標(biāo)準(zhǔn)化、依賴管理、構(gòu)建生命週期自動化和插件擴(kuò)展;1.使用pom.xml定義groupId、artifactId、version和dependencies;2.掌握核心命令如mvnclean、compile、test、package、install和deploy;3.利用dependencyManagement和exclusions管理依賴版本與衝突;4.通過多模塊項目結(jié)構(gòu)組織大型應(yīng)用並由父POM統(tǒng)一管理;5.配

Python通過參考示例 Python通過參考示例 Jul 29, 2025 am 12:31 AM

Python中函數(shù)傳參是“傳遞對象引用”,即1.對於可變對象(如列表、字典),函數(shù)內(nèi)進(jìn)行原地修改(如append、賦值切片)會直接影響原對象;2.對於不可變對象(如整數(shù)、字符串),函數(shù)內(nèi)無法改變原對象,重新賦值只會創(chuàng)建新對象;3.參數(shù)傳遞的是引用的副本,若在函數(shù)內(nèi)重新綁定變量(如lst=[...]),則斷開與原對象的連接,不影響外部變量。因此,修改可變對象會影響原數(shù)據(jù),而不可變對象和重新賦值則不會,這解釋了為何列表在函數(shù)內(nèi)修改後外部可見,而整數(shù)變化僅限局部。

See all articles