iOS(Object C) 递归方法求和

news/2024/9/24 20:27:00/

有等差数列1,2,3,4,5使用递归方法求和:

- (int)sum:(int)value
{if (value >5){return self.count;}//在外面定义一个全局变量self.count,初始值为0self.count = [self sum:value+1] + value;return self.count;
}

调用验证:

 self.count = 0;
int result = [self sum:1];

不一定使用等差数列求和,无序数组也行

- (void)sum1:(NSMutableArray *)array Index:(int)index
{if (index > (int)array.count-1){return;}[self sum1:array Index:index+1];//在外面定义一个全局变量self.count,初始值为0self.count =  self.count + [array[index] intValue];NSLog(@"self.count==%d",self.count);
}

验证代码:

    self.count = 0;NSMutableArray * array = [[NSMutableArray alloc]initWithObjects:@"11",@"6",@"8",@"65",@"33",@"56", nil];[self sum1:array Index:0];


http://www.ppmy.cn/news/1437130.html

相关文章

从0开始用C写贪吃蛇(基于链表)

目录 1. 游戏背景 2. 游戏效果演示​编辑​编辑​编辑 3. 实现目标 4. 技术要点 5. 控制台程序 5.1 设置控制台窗口的长宽和名字 5.2 控制台屏幕上的坐标COORD 6.Win32 API 6.1 GetStdHandle 6.2 GetConsoleCursorInfo 6.3 CONSOLE_CURSOR_INFO 6.4 SetConsole…

Docker:学习笔记【1】

文章目录 Docker简介Docker基本使用步骤Docker局限性Docker主要概念镜像与容器DockerHubDocker架构Docker与虚拟机参考链接Docker简介 Docker 是一个开源的容器化平台,可以帮助开发者将应用程序及其依赖项封装为一个可移植的容器,然后可以在不同的环境中运行。Docker利用容器…

Windows电脑中护眼(夜间)模式的开启异常

我的电脑是联想小新16pro,Windows11版本。之前一直可以正常使用夜间模式,但是经过一次电脑的版本更新之后,我重启电脑发现我的夜间模式不能使用了。明明显示开启状态,但是却不能使用,电脑还是无法显示夜间模式。 询问…

广工电工与电子技术实验报告-8路彩灯循环控制电路

实验代码 module LED_water (clk,led); input clk; output [7:0] led; reg [7:0] led; integer p; reg clk_1Hz; reg [7:0] current_state, next_state; always (posedge clk) begin if(p25000000-1)begin …

vscode中对 python 快速增加header 描述

在首选项→配置用户代码片段→python 然后再 Code/User/snippets/python.json文件中写入 {// Place your snippets for python here. Each snippet is defined under a snippet name and has a prefix, body and // description. The prefix is what is used to trigger the …

FA-128晶振用于医疗设备

血糖仪已成为家庭常用的医疗设备,日本爱普生晶振公司生产的2016封装,32MHz贴片晶振可完美应用于医疗器械血糖仪,此款晶振订货型号为X1E000251005900晶振,型号为FA-128,负载电容分8PF,精度10PPM,其尺寸参数为2.0x1.6x0.5mm,符合ROHS标准且无铅,具有封装尺寸超小,高精度,频率范围…

51单片机中断和定时的结合应用

#include <reg52.h>unsigned int cnt 0;sbit led P1^1;// 初始化定时器 void TimerSetup(){TMOD 0x01; // 定时器的第1个模式TH0 0xB8; // 定时器的初始值-高位TL0 0x00; // 定时器的初始值-低位TR0 1; //启动定时器cnt 0;EA 1; // 开启总中断ET0 1; // 时间中断…

【vue,unapi】UniApp引入全局js实现全局方法,全局变量

创建一个全局文件utils.js export const baseUrl "https://www.baidu.com/"export const fn () > {console.log("demo"); } export const obj {baseUrl : "https://www.baidu.com/",demo(){console.log("demo2");} }第一种&#…