gpt4 book ai didi

将迭代算法转换为递归算法

转载 作者:行者123 更新时间:2023-11-30 21:42:16 25 4
gpt4 key购买 nike

我编写了以下程序:

#include <stdio.h>

void printValue();

int main (){
int n = 100;
int i;
for (i=0; i<n; i+=1)
printValue();
}


void printValue(){
static unsigned int y = 0;
printf("y = %d", y);
y+=1;
}

如何重写算法以使其递归?

最佳答案

#include <stdio.h>

void printValue(void);
void times(int n, void (*func)(void)){
if(n>0){
func();
times(--n, func);
}
}

int main (void){
int n = 100;
times(n, printValue);
return 0;
}

void printValue(void){
static unsigned int y = 0;
printf("y = %d\n", y);
y+=1;
}
<小时/>
#include <stdio.h>

void printValue(int);
void repeat_upto(int init_value, int end_value, int incremental,
void (*func)(int)){
if(incremental < 0 ? init_value >= end_value : init_value <= end_value){
func(init_value);
repeat_upto(init_value + incremental, end_value, incremental, func);
}
}

int main (void){
repeat_upto(0, 100-1, +1, printValue);
return 0;
}

void printValue(int v){
printf("%d\n", v);
}
<小时/>
#include <stdio.h>

void printValue(int v, int end_value){
if(v < end_value){
printf("%d\n", v);
printValue(v+1, end_value);
}
}

int main (void){
printValue(0, 100);
return 0;
}

关于将迭代算法转换为递归算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27892071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com