Sunday, July 26, 2009

Can someone fix this code, or tell me what is wrong in simple terms and what to do?

#include %26lt;iostream%26gt;





int add(int x, int y)


{


return x + y + x;


}





int main()


{


int x = 3;


int y = 5;


using namespace std;


cout %26lt;%26lt; "The sum of 3 plus 5 plus 3 is: " %26lt;%26lt; add(3, add(3, 5)) %26lt;%26lt; endl;


return 0;


}








I want it to give me the answer 11. 3 + 5 + 3. What did I do wrong. C++. Visual C++ 2008 Express. It tells me the answer is 17???

Can someone fix this code, or tell me what is wrong in simple terms and what to do?
dude. Look at your return statement : x + y + x


so ...


add(3, add(3, 5)) =


add(3, 3 + 5 + 3) =


add(3, 11) = 3 + 11 + 3 = 17





Software always does exactly what you tell it to do...
Reply:Your add function is incorrect. It should just return:





return x + y;





That should do it.
Reply:Well look at the code...





add(3, add(3, 5))





The inside call is executed first: add(3,5) which will return 3+5+3 = 11. Then you're calling add(3,11), which adds 3+11+3 = 17.





If you want it to just add 3+5+3, then just have a single call to the add function: add(3,5). Or change your add function to return just x+y.

birthday flowers

No comments:

Post a Comment