how to think c++ output about this code
Sep 2, 2017 at 9:02am UTC
I can't understand the funz function, how I can think this code?
i have only this idea:
12 is != 0
return is 12+funz(12,10)
then x=12 y=10
10 is != 0
return is 12+10+funz(10,2)
then x=10 y=2
2 is != 0
return is 12+10+2+funz(2, 0)
then x=2 y=0
0 is = 0
return x (26)
t=26
that's right?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
using namespace std;
int funz(int , int );
int main()
{
int a=10, b=12, t;
t = funz(a, b);
cout << "t = " << t << endl;
return 0;
}
int funz(int x,int y)
{
if (y!=0){
cout << y+funz(y, x%y) << endl;
return (y+funz(y, x%y)); }
else
return x;
}
Sep 2, 2017 at 11:00am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <iostream>
int funz(int , int );
int main()
{
std::cout << "0. in main\n" ;
int a = 10, b = 12 ;
const int t = funz(a, b) ;
std::cout << "0. back in main: t == " << t << '\n' ;
}
std::ostream& spaced_cout( int n )
{
for ( int i = 0 ; i < n*8 ; ++i ) std::cout << ' ' ;
return std::cout << n << ". " ;
}
int funz( int x, int y )
{
static int cnt = 0 ;
++cnt ;
spaced_cout(cnt) << "enter funz( " << x << ", " << y << " )\n" << std::flush ;
if ( y!=0 )
{
spaced_cout(cnt) << "call funz( " << y << ", " << x << '%' << y << " )\n" ;
const int v = funz( y, x%y ) ;
spaced_cout(cnt) << "return " << y << " + " << v << " == " << y+v << '\n' ;
--cnt ;
return y+v ;
}
else
{
spaced_cout(cnt) << "return " << x << '\n' ;
--cnt ;
return x ;
}
}
0. in main
1. enter funz( 10, 12 )
1. call funz( 12, 10%12 )
2. enter funz( 12, 10 )
2. call funz( 10, 12%10 )
3. enter funz( 10, 2 )
3. call funz( 2, 10%2 )
4. enter funz( 2, 0 )
4. return 2
3. return 2 + 2 == 4
2. return 10 + 4 == 14
1. return 12 + 14 == 26
0. back in main: t == 26
http://coliru.stacked-crooked.com/a/0d72817dd81e1afc
Topic archived. No new replies allowed.