Need help in a little C++ program

Started by
4 comments, last by Kingknz 24 years, 1 month ago
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; }
Advertisement
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
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.

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
Also, you''re declaring old_answer to be an int, but ints can''t hold decimals. So, old_answer is probably being rounded up to 1 or down to 0. Change it to a float or double and that part will work.


- null_pointer
Sabre Multimedia
Use double, floats tend to cause hard to find bugs

This topic is closed to new replies.

Advertisement