gpt4 book ai didi

c - 如何更改代码,创建递归函数

转载 作者:太空宇宙 更新时间:2023-11-04 07:45:55 24 4
gpt4 key购买 nike

我注册了一门名为 CS50 的类(class)。我最近一直在学习递归函数,虽然我创建了一个名为 Collat​​z 的程序,它可以完成我想要它做的事情,但它内部没有递归函数,因为该函数不会调用自身。我被卡住了,我想不通,我应该如何实现一个递归函数,使其看起来整洁干净并调用自身。

我试图在我的主要功能旁边实现一个功能。但是我不知道那个函数应该是什么样子,它又是如何调用自己的。

//int x(int n);

int main(void)
{
int n;
//j is a counter for the number of times 'n' has to be calculated to get n==1
int j = 0;

//Ask for an integer
printf("Int: ");
scanf("%i", &n);

//Check for 0 or less
if (n <= 0)
{
printf("ERROR.")
return 1;
}

//This is where recursion should be implemented
while (n != 1)
{
if (n % 2 != 0)
{
while ((n % 2) != 0)
{
n = 3*n + 1 ;
j++;
}
}
else if ((n % 2) == 0)
{
while (n != 1)
{
n /= 2;
j++;
}
}
}
printf("N: %i, number of times: %i \n", n,j);
}

/*
int x(int n)
{
Should a recursive function be implemented here?
}
*/

输出正常。输出应该是数字 n,它应该始终为 1,以证明程序有效并始终到达数字 1,以及从 n 到 1 需要多少步。

最佳答案

给你。:)

#include <stdio.h>

unsigned int collatz( unsigned int n )
{
return n < 2 ? 0 : 1 + collatz( n % 2 == 0 ? n / 2 : 3 * n + 1 );
}

int main(void)
{
while ( 1 )
{
unsigned int n;

printf( "Enter a non-negative number (0 - exit): " );

if ( scanf( "%u", &n ) != 1 || n == 0 ) break;

printf( "The number of steps is %u\n\n", collatz( n ) );
}

return 0;
}

程序输出可能是这样的

Enter a non-negative number (0 - exit): 19
The number of steps is 20

Enter a non-negative number (0 - exit): 0

关于c - 如何更改代码,创建递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57060678/

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