Eng*_*999 -5 c++ recursion function
我这里有一个程序,它总是将数字的数字相加,直到我得到一个数字.例如,给定num = 38,过程如下:3 + 8 = 11,1 + 1 = 2.由于2只有一位数,所以返回它.
问题是,返回main的值是垃圾,但是在从函数addDigits()返回值之前,它是正确的值.谁能在这看到我的错误?这让我疯狂.提前谢谢了.
#include <iostream>
#include <vector>
#include <stdio.h>
using namespace std;
int addDigits(int num)
{
vector <int> nums;
if (num <10)
{
return num;
}
int rem, temp = 0;
while (num > 9)
{
temp = num /10;
rem = num %10;
nums.push_back(rem);
num = temp;
}
nums.push_back(num);
int total = nums[0];
for (int i = 1; i < nums.size(); i++)
{
total += nums[i];
}
cout<<"total :"<<total<<endl;
if (total >= 10)
{
addDigits(total);
}
else
{
return total;
}
}
int main()
{
int val = 0;
int total = 0;
while(1)
{
cout<<"Enter a number : "<<endl;
cin>>val;
total = addDigits(val);
cout<<total<<endl;
}
}
Run Code Online (Sandbox Code Playgroud)
您不返回递归调用:
addDigits(total);
//should be
return addDigits(total);
Run Code Online (Sandbox Code Playgroud)
您应确保在编译器中打开警告以捕获此类问题.例如,GCC发出此警告:
警告:控制到达非空函数的末尾[-Wreturn-type]
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |