Re: help needed

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hello Naga,

On Sat, Jun 05, 2004 at 07:55:40PM -0700, Naga Raju Thogiti wrote:
> Hi,
> I am writing C++ program for displaying a table of tangents given the
> lower and upper limits. The program initially rounds off ( e.g if one
> enters 29.58 and 30.33, it rounds off it to 29.6 and 30.3), and output the
> result in a table form. I have this problem with displaying the table
> completely and correctly, it was challenging for me to figure out where
> was I going wrong? Can you please help me out with it.
> 
> When I entered, 29.58 30.33 it stops at 30.2, for 32 34, it stops at 33.9
> but when I entered 84.14 84.44 and 89.44 89.48 it gives me correct table.

At first, please note that this list is about the usage of or problems with 
GCC, the GNU Compiler Collection. Skimming through your post I haven't found
the word gcc / g++ etc. not a single time. This makes me suspect that your 
problem would've been better addressed somewhere else. 

Anyway, to answer your question:

You need to remember that floating point numbers are inherently imprecise
and that you can't expect that if you add 0.1 to a floating point number
that its value will increase exactly by 0.1 nor that 0.1 itself can be 
exactly represented as a floating point number.

>  //cout<<"\n\t "<<min_Value<<" "<<max_Value;

You can't see a difference here because you've set the precision of cout to 4.

Just issue a "cout << setprecision(50);" right before the (uncommented)
line above and you'll see what I mean.

You probably want to round the min_Value in every iteration, e.g.

  min_Value = floor(min_Value*10 + 1) / 10;

This is not much better, but it avoids that the inaccuracies add
up too much during the loop.

Or, you may compute the numbers of iterations before entering the loop
and use an integer variable to do the counting. Something along the lines of

  for (int i = static_cast<int>((max_Value - min_Value) * 10)); 
       i >= 0; --i) 
    // ...


A few notes about your code:

You're using the old C++ headers. In new code you might want to use
standard headers like 'iostream' instead of the antiquated 'iostream.h', 
'cmath' instead of 'math.h' et cetera.

> void main ()

This *needs* to be "int main(void)".

> for (int j = 1;j<=100;j++)
> {
>  cout<<"-";
> }

You might find it easier (or at least shorter) to write 
'cout << string ("-", 100);' instead of the above.

Cheers.
-- 
Claudio

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux