Archived

This topic is now archived and is closed to further replies.

Kingknz

Need help in a little C++ program

Recommended Posts

Basically, I wrote the console program below, and it functions as I want it to, however, for some reason, if I want to increase the accuracy of the answer (i.e. use float types instead of integers for all variables), I get weird bugs etc (eg. the while statement never becomes false, etc). Sooo.. If anyone knows how to rewrite this progy with improved accuracy, please give me a hand! Thanks ========== #include #include #include #include #include int main(int argc, char* argv[]) { int signed length, width, answer, old_answer, x; answer = 1.0; old_answer = 0.5; x = 1; printf("Enter length: \n"); scanf("%d", &length); printf("Enter width: \n"); scanf("%d", &width); while (answer > old_answer) { x = x + 1; old_answer = answer; answer = ((length * width * x)+(((length * -2)+(width * -2)) * x * x)+(4 * x * x * x)); } printf("Maximum volume: %d \n", old_answer); printf("X is equal to: %d \n", x - 1); return 0; }

Share this post


Link to post
Share on other sites
well, first off, you''ll need to change your coversion thingys in your printf and scanf statements for float values (%d to %f), and thats about all i can see because im not familiar with what you''re trying to do (too many things goin'' on )

also, you could change x = x + 1 (the VB way), to x += 1 (the C way). Doesn''t make it any faster, but if you have a huge variable like gv.stuffhere.morethings.more[index].x, you don''t have to type it twice That methiod applies to multiplying, subtracting, etc.

Sorry if I didn''t solve your problem like with the WHILE error or anything, but I''m just trying to help out all I can, anyway

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
while (answer > old_answer)
{
x = x + 1;
old_answer = answer;
answer = ((length * width * x)+(((length * -2)+(width * -2)) * x * x)+(4 * x * x * x));
}

There is a potential problem in the logic.
answer = l*w*x-2l-2w*x^2+4x^3
For mathematical purposes, you can simplify the equation to 4x^3 as x increases towards infinity.
So as your x becomes bigger, the only part of the equation that only matters is 4x^3, and since x is always increasing, the while loop will go on forever.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
If you use floats, then first of all you''d have to use %f instead of %d (like the others said), but, more importantly, you can''t compare floats in the while loop!
It''s very simple: floats are no precise numbers (like int etc), they are approxiamtions of numbers. So, you''d either have to convert them to ints, or use a different algorithm.

Erik

Share this post


Link to post
Share on other sites