Sunday, August 2, 2009

C programming question....?

We have the following function: f(x)=500x-10x². Write a program that finds the value of x that maximizes f(x). Your program should print out the value of f(x) for each value of x. It should also print out which value of x produced the maximum value of f(x). In writing your program, you should do the following:





(a) In the header of your source code, include the pseudo code you used to design your program.





(b) Use a brute-force approach to find the answer. That is, create a loop that tries values of x from 0 to 50 (intergers only) in order to determine which value maximizes the function.





(c) Use x*x instead of the math.h function pow() for finding x². This will allow you to use a variable type of int for all variables.

C programming question....?
You need to loop over the values 0 to 50. Inside the loop you need to evaluate the function.





You also need to keep track of the running maximum and compare it with each value you calculate. When you find a bigger value, you save it away as the new running maximum.





You also need to save away the x value that produced your running maximum when you save the new running maximum.





So inside the loop you need something like





if (f %26gt; fmax)


{


....fmax = f;


....xmax = x;


}





There is one really tricky thing, and that is you have to initialize your running maximum. Otherwise the first time you execute that if statement the value will be undefined. One way is to initialise it to f(0) and loop from 1 to 50. Another is to initialize it to -INT_MAX (you need to #include something to get that, might be %26lt;limits.h%26gt; but can't remember offhand).





Good luck.


No comments:

Post a Comment