Saturday, May 22, 2010

I would like to retrieve the output for exp(-1/2x) with a visual c++ compiler but all i get is 1. Please help.

#include%26lt;iostream%26gt;


#include%26lt;cmath%26gt;





int main()


{


using namespace std;


float y,x;





for(x=0;x%26lt;8;)


{


y = exp((-1/2)*x);


cout%26lt;%26lt;"y= "%26lt;%26lt;y%26lt;%26lt;"\n";


x = x + 0.1;


}





return 0;


}





Here's my attempt to code the function. What should I add?

I would like to retrieve the output for exp(-1/2x) with a visual c++ compiler but all i get is 1. Please help.
The problem lies in your "(-1/2)" portion of your code...change that to be "-0.5" ... that will solve your problem..





The reason why it didnt work is because in C/C++ when you have take 1/2 that says to the CPU to take two integers and the result is an integer and since 1/2 is 0.5 as a float BUT as an integer it is "0" so now your line will always try to do a exp(0) which means y will always equal to "1"....So either you change (-1/2) to be (-0.5) or you add a ".0" to the 1/2 ... such as "-1.0/2" or "-1/2.0" or "-1.0/2.0"...All those can fix your problem but the most elegant and fastest for the process would be to use "-0.5".

sweet pea

No comments:

Post a Comment