日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java 简单的加法 递归 从A加到B

發布時間:2025/3/11 编程问答 12 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 简单的加法 递归 从A加到B 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
public class Main {// 設置保存和的變量static int sum = 0;public static void main(String[] args) {int begin = 1, end = 10;// 調用方法一 sum =0;sum = add(begin, end);System.out.println("===>>> 從 " + begin + " 開始加到 " + end + " 的結果是" + sum);System.out.println();// 調用方法二sum =0;addB(begin, end);System.out.println("===>>> 從 " + begin + " 開始加到 " + end + " 的結果是" + sum);System.out.println();}// 方法一(從尾處開始加)public static int add(int begin, int end) {if (begin <= end) {sum = sum + end;System.out.println("當前begin為 " + begin + " 當前end為 " + end + " 當前sum為 " + sum);add(begin, end-1);}return sum;}// 方法二(首尾同時加)public static void addB(int begin, int end) {if (begin <= end) {sum = sum + begin + end;System.out.println("當前begin為 " + begin + " 當前end為 " + end + " 當前sum為 " + sum);addB(begin + 1, end - 1);}} }

結果:

當前begin為 1 當前end為 10 當前sum為 10
當前begin為 1 當前end為 9 當前sum為 19
當前begin為 1 當前end為 8 當前sum為 27
當前begin為 1 當前end為 7 當前sum為 34
當前begin為 1 當前end為 6 當前sum為 40
當前begin為 1 當前end為 5 當前sum為 45
當前begin為 1 當前end為 4 當前sum為 49
當前begin為 1 當前end為 3 當前sum為 52
當前begin為 1 當前end為 2 當前sum為 54
當前begin為 1 當前end為 1 當前sum為 55
===>>> 從 1 開始加到 10 的結果是55


當前begin為 1 當前end為 10 當前sum為 11
當前begin為 2 當前end為 9 當前sum為 22
當前begin為 3 當前end為 8 當前sum為 33
當前begin為 4 當前end為 7 當前sum為 44
當前begin為 5 當前end為 6 當前sum為 55
===>>> 從 1 開始加到 10 的結果是55

總結

以上是生活随笔為你收集整理的java 简单的加法 递归 从A加到B的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。