注册 登录
编程论坛 C++教室

请教 n 没有被赋初值,为什么能正确运行谢谢!

vvvevvv 发布于 2014-09-28 09:47, 471 次点击
共5个人甲乙丙丁戊,甲是10岁,依次大两岁。求戊的岁数(戊为18岁)。
#include<iostream>
using namespace std;
int age(int n);
int main()
{
    cout<<age(5)<<endl;
    return 0;

}
int age(int n)
{
    int c;
    if(n==1) c=10;
    else c=age(n-1)+2;
    return c;
}



定义函数的时候 n没有被赋初值。这个函数看的有点糊涂, 朋友帮分析一下 谢谢。还有一个问题:age函数为什么不在n==1的时候停止呢。

[ 本帖最后由 vvvevvv 于 2014-9-28 09:56 编辑 ]
5 回复
#2
peach54602014-09-28 10:48
age(5)
这不是赋值了么
#3
stop12042014-09-28 17:42
你age传入参数 5
程序代码:
int age(n = 5)
{
    int c;
    if(n==1)    // n = 5
         c=10;  // flase
    else
         c=age(n-1)+2; //c=age(5-1)+2;      c=6
    return c;   //return 6
}
#4
stop12042014-09-28 17:53
你可以这么做:
程序代码:

#include<iostream>
using namespace std;
int age(int n,int i);    //n为甲岁数   i为人数
int main()
{
    cout<<age(10,5)<<endl;
    return 0;

}
int age(int n,int i)
{
    if (--i == 0)
        return n;
    age(n+2,i);   
}
// age(10,5)
/*
if (--5 == 0)
       return n;
    age(10+2,4);        // 4  =  --5  
            {   
                age(12,4)
                   if (--4 == 0)
                        return n;
                    age(12+2,3);   
                    ....
                    ...
                    ..
           }
*/


#5
韶志2014-09-28 22:13
n 是你 age() 函数的形参,调用函数时传个值就OK了   

age(5),就是把 5 传给了 n
#6
vvvevvv2014-09-29 09:17
明白了 多谢指导了!
1