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

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

Java 中的階乘

Aug 30, 2024 pm 04:25 PM
java

在本文中,我們將了解使用 Java 編程語言編寫用于階乘計算的代碼的各種方法。作為一種易于使用的面向?qū)ο笳Z言,Java 是一種獨立于平臺的簡單編程語言。 Java 的編譯器和解釋器是以安全性為主要方面開發(fā)的。 Java 的應(yīng)用范圍非常廣泛。

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

開始您的免費軟件開發(fā)課程

網(wǎng)絡(luò)開發(fā)、編程語言、軟件測試及其他

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

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

1.完成您的代碼并將其另存為 (文件名).java

2.打開終端并運行以下 java 命令。

  • a. javac(文件名).java

3.上面的命令將生成一個類文件。

4.現(xiàn)在,執(zhí)行類文件。

  • a. java(文件名)

使用各種方法的階乘示例

以下是使用不同方法的不同示例:

示例 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 擴展名保存上述代碼。

代碼說明:

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

輸出:

Java 中的階乘

示例 2 – 使用用戶輸入

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

參考以下代碼進行基于用戶輸入的計算:

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);
}
}
}

像前面的示例一樣保存上面的代碼。

代碼說明:

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

輸出:

Java 中的階乘

示例 3 – 使用遞歸方法

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

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

缺點

遞歸的缺點:

  • 基本上,調(diào)試遞歸代碼并跟蹤它是否有錯誤的步驟是相當(dāng)困難的。
  • 除此之外,遞歸會使用更多內(nèi)存,因為它使用堆棧來完成任務(wù),并不斷通過更新的遞歸調(diào)用來累加堆棧。
  • 而且,如果實施不明智,遞歸會減慢函數(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 中的階乘的詳細內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

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

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

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

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的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é)合原生表達式以提升安

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

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

以身作則 以身作則 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會強制表格列寬由第一行單元格寬度決定,避免內(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負載示例 Python JSON負載示例 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)建的標準工具,答案在于它通過pom.xml實現(xiàn)項目結(jié)構(gòu)標準化、依賴管理、構(gòu)建生命周期自動化和插件擴展;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)進行原地修改(如append、賦值切片)會直接影響原對象;2.對于不可變對象(如整數(shù)、字符串),函數(shù)內(nèi)無法改變原對象,重新賦值只會創(chuàng)建新對象;3.參數(shù)傳遞的是引用的副本,若在函數(shù)內(nèi)重新綁定變量(如lst=[...]),則斷開與原對象的連接,不影響外部變量。因此,修改可變對象會影響原數(shù)據(jù),而不可變對象和重新賦值則不會,這解釋了為何列表在函數(shù)內(nèi)修改后外部可見,而整數(shù)變化僅限局部。

See all articles