Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 用于检查数字的递归函数_C++_Function_Recursion - Fatal编程技术网

C++ 用于检查数字的递归函数

C++ 用于检查数字的递归函数,c++,function,recursion,C++,Function,Recursion,编写一个递归函数,检查数字中有多少位可以被后面的数字除。示例:84963应该返回2,因为8可以被4除,6可以被3除。我的函数似乎根本没有输出任何东西 #include <iostream> using namespace std; int fun (int n); int main() { int n; cin >> n; cout << fun(n) << endl; return 0; } int fun

编写一个递归函数,检查数字中有多少位可以被后面的数字除。示例:
84963
应该返回2,因为8可以被4除,6可以被3除。我的函数似乎根本没有输出任何东西

#include <iostream>

using namespace std;

int fun (int n);

int main()
{
    int n;
    cin >> n;
    cout << fun(n) << endl;
    return 0;
}

int fun(int n){
    int count = 0;
    if (fun(n % 100) % fun(n % 10) == 0)
        count++;
    return count;
}
#包括
使用名称空间std;
int fun(int n);
int main()
{
int n;
cin>>n;
库特

只需拉一对,尝试除法,然后切掉最后一个数字并重复。

你的递归现在没有多大意义。更合乎逻辑的方法是看看最后一个数字(在
321
中的so
1
)当前是否可以除掉最后一个第二个数字(在
321
中的so
2
)。您可以通过定义一个函数来执行此操作,该函数检查是否可能,并递归传递除以10的数字。该函数如下所示:

int fun(int n)
{
  if (n < 10)
    return 0;
  int last = n % 10;
  n = n / 10;
  int secondlast = n % 10;
  if (secondlast != 0 && last != 0 && secondlast % last == 0) 
    return 1 + fun(n);
  else
    return fun(n);
}
intfun(intn)
{
如果(n<10)
返回0;
int last=n%10;
n=n/10;
int secondlast=n%10;
如果(secondlast!=0&&last!=0&&secondlast%last==0)
返回1+乐趣(n);
其他的
返回乐趣(n);
}
更新说明:在查看莫斯科评论中的Vlad之后,我将条件的
last!=0
部分向前移动,以解决一个bug(除以0)


来自莫斯科的Vlad谈到的问题如下:例如,如果你想将
04
部分计算为0,你应该使用上面的代码。否则你应该删除
secondlast!=0
部分。

你实际上没有更新
n
值,因此你进入了一个无限循环,另一方面,您的函数最初只针对3位数字设计。我认为它应该类似于:

int fun(int n, int ant, int count){
    if( n == 0 )
        return count;

    if (ant != 0 &&
             (n%10) % ant == 0)
        count++;

    return fun(n/10, n%10, count);
}
我应该使用不同的位数。

有效代码将为

size_t fun( int n )
{
    const int base = 10;
    int digit = n % base;
    n /= base;

    return ( n == 0 ? 
             0      : 
             ( digit && n % base && !( n % base % digit ) ) + fun( n ) );
}

您应该使用调试器并查找值……您会学到很多东西。您是否尝试过我的建议?通过使用3个参数而不是1个参数,您将提高内存使用率(在处理大数字时非常重要)似乎崩溃..我检查了调试器,但由于某种原因调试器变为0,这可能是原因?可能是崩溃I来自
n
being
0
@user3002211,很抱歉没有测试。我修复了问题。@Patrick Kostjens这是一个问题,因为在本例中,secondlast%last==0@VladfromMoscow,问题其实有点复杂不同。请参阅我的更新。
size_t fun( int n )
{
    const int base = 10;
    int digit = n % base;
    n /= base;

    return ( n == 0 ? 
             0      : 
             ( digit && n % base && !( n % base % digit ) ) + fun( n ) );
}