Simple polygon area c++ prog. problems
I made a c++ program a while ago, but never did understand why it only partly worked.
Code:
# include <iostream> I enter in 5 at a DOS screen (I just happen to be using Windows), and get the correct info back. The area of a regular 5 sided poly of perimeter 1000m is 68819.1 m^2. Quote:
Quote:
I'm still a newb to programming, so any help as to why this is happening would be gladly accepted. |
Hi
me and math don't really go well together, but there's something i noticed in your code: Quote:
there are 2 reasons for that: 1) to increase readability of the code. if someone else reads the code, they know that you indeed meant what you wrote and not did a mistake(and when debugging someone else's code something like that can cause a LOT of trouble based on my experience) 2) to make sure you don't accidently ignore the precedence of a certain operator. for example, i once ignored the precedence of the operator & as a bitwise AND. something which caused my program to return erroneous results in several locations. i don't know if it has anything to do with the problem you have, but IMHO i believe that's a more clear and safe way to write code. |
Thanks for the pointer, I added some parenthesis to my code, if anyone as a notion of what is going wrong and wants me to post the code with parenthesis just say the word. However, the problem of erroneous returns is still there. I'm compiling with the Borland bcc32 btw.
|
by Hal
height = 500/sides * tan_angle; base = 1000/sides; youve been caught out by integer division, an expression evaluates to the type of its most precise component, your dividing two ints and thus getting an int back, either make the numbers floating point ie 500.0, 1000.0 or cast them to floats/doubles as a side note your formula can be simplified, generally the less fp math you do the more accurate your results so you might want to use area = 250000*tan(angle)/n |
Aha! Thank you Stor_G and Kev82! I made my formula "dumb" so that I could make sure that things were working before I simplified it. I can cut down a lot of maths now. (: Again, thanks a lot, I never did get it working until now.
|
All times are GMT -5. The time now is 06:17 PM. |