以相反顺序的正十进制整数的递归函数数字 C++ [英] recursive function digits of a positive decimal integer in reverse order c++
本文介绍了以相反顺序的正十进制整数的递归函数数字 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一项作业要编写一个递归函数,该函数以相反的顺序写入正整数的数字.我的问题是该函数不能正确显示反向.我知道我应该在递归调用中显示 10 的数量和/时使用 % 或 10 以及基本情况应该是 <10. 这是我的代码.
I have an assignment to write a recursive function that writes the digits of a positive integer in reverse order. My problem is that the function doesn't display the reverse correctly. I know im supposed to use % or 10 when displaying the number and / of 10 when in the recursive call as well as the base case is supposed to be < 10. Here is my code.
#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
推荐答案
我认为这就是你的功能应该是:
I think this is what your function should be:
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
}
}
这篇关于以相反顺序的正十进制整数的递归函数数字 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文