What's new

Closed Why output is 32?

Status
Not open for further replies.

portfolio101

Eternal Poster
Joined
Nov 22, 2015
Posts
1,366
Solutions
1
Reaction
315
Points
380
Mga boss pa help naman. Nalilito kasi ako bakit 32 ang output nya. Hindi rin ako mka debug o ma try sa pc or laptop dahil nasira.

Ito po yong code

#include <iostream>
using namespace std;


int glob=10;
int f(int x){
int glob=3;
int result;
result=(3*x)+2;
return result;

}

int main() {

int b;
int x=3;
int y=4;

b=f(glob) ;

return 0;
}

Output:32
 
because int glob = 10 is declared as a global variable, as you can see on the f function you created that there is already a parameter int x which already has the value of 10 coming from the main function b=f(glob),. The glob variable declared locally in the f function is actually never used, Tama ang code to output 32. but if ibang output gusto mo like 11, mali ang flow ng code mo.
 
kung gusto mo 11 dapat
value ng x is 3
b=f(x);

kasi sa function ng f
mag rereturn sya ng result=(3 * 3)+2; which is 9 + 2 = 11
so pag nag cout<<b; ang output nyan is 11

dun naman sa ginawa mo, dalawang variable mo na glob,para sa function na f and para sa main class

tapos meron kang b=f(glob);
ang kukunin nya na glob is naka global na may value na 10 hindi nya kukunin yong glob na value is 3 kasi para lang sya kan f unction, kaya nag output na 32 kasi pinasahan mo si f function ng parameter na glob na ang value 10 tapos mag rereturn kaya nakuha yong 32 kasi result=(3 * 10) + 2= 32


sana naka tulong sayo itong explanation hehehe
 
Last edited:
global variable ang 'glob' na ginamit na parameter sa 'f' function, no use 'yung pag aassign ng new value sa 'glob' na nasa scope ng 'f' function dahil ang 'x' ang ginamit sa substitution sa constructor ng function.

sa madaling sabi, magkaiba ang 'glob' variables, global 'glob' at scoped 'glob', bali gagana lang ang scoped 'glob' sa loob ng scoped area, pangmalawakan nanan ang global :)

isa pa pala, naipasa na ang global 'glob' sa 'int x' parameter ng 'f' function kaya no use ang scoped 'glob' dahil 'x' ang ginamit sa 'result' variable. kung may 'glob' variable ka sa loob ng 'f' function, yun ang may value na 3. happy coding!
 
Simple and plain. global variable 'glob' was declared and initialized with a value of 10 which served as the multiplier of the value 3 inside the f function which expression is written as (3*x) where the x is simply the argument passed from f function parameter which was 10(global variable 'glob'). To put it simple, you made the expression as : (3*10) + 2 kaya sya naging 32. that if you are trying to output that result. If 11 then you might missing something from the expression.
 
Last edited:
Status
Not open for further replies.

Similar threads

Back
Top