正十进制整数的递归函数数字,以相反的顺序c
作者:互联网
我有一项工作要写一个递归函数,该函数以相反的顺序写一个正整数的数字.我的问题是该功能无法正确显示反向.我知道我应该在显示数字时使用%或10,而在递归调用中以及在基本情况应该为<时使用10的/. 10.这是我的代码.
#include <iostream>
using namespace std;
int reverse(int,int);
int main()
{
int number;
int n;
cout << " Enter number to reverse." << endl;
cin >> number;
cout << reverse(number % 10,0);
return 0;
}//end main
int reverse(int number,int n)
{
if(n < 10)
{
return n;
}
else
{
return reverse(number/10,n);
}
}// end reverse
解决方法:
我认为这是您的职能应为:
void reverse(int number){
if(number == 0) //base/basic case i.e if number is zero the problem is already solved, nothing to do, so simply return
return;
else{
cout << number % 10; // print that last digit, e.g 103%10 == 3
reverse(number/10); //solve the same problem but with smaller number, i.e make the problem smaller by dividing it by 10, initially we had 103, now 10
}
}
标签:digits,c,variable-assignment,reverse 来源: https://codeday.me/bug/20191011/1891469.html