View Full Version : Another dumb C++ Question


Nebula
05-01-04, 12:12 AM
Sorry for cluttering this forum with my newb questions ;).

One of my latest assignments is to write a small prog that calculates the area of an octagon.


#include <iostream.h>
#include <math.h>

#define oct_const 4.828

int main()
{

float a, area_octagon;

cout << "Enter the length of one side: ";

cin >> a;

area_octagon = oct_const * pow(a,2);


cout << "The area of the octagon with side length " << a <<" = ";

cout.precision(3);
cout.setf(ios::showpoint | ios::fixed);

cout<< area_octagon << endl << endl;


return 0;

}

When I build it I get a warning from line 15 "conversion from 'double' to 'float', possible loss of data". It still compiles, but I can't get rid of this warning. I've tried casting it as a double but it still doesn't work!

What am I doing wrong?

Thanks again!

curioucity
05-01-04, 03:54 AM
I'm very bad at C++, but I think I can help a little... hopefully....
Maybe you can try declaring oct_const, instead of that way, into this:

float oct_const=4.828;

That should tell the compiler that the constant is pure float. I've never used '#define' anyway... confuzzing.....

okinrus
05-01-04, 04:19 AM
curioucity is right in that you shouldn't use define unless you absolutely have to. But the reason you are getting this warning is that pow returns a double, oct_const * pow(a, 2) will have a type double, and then you are assigning a double to a float causing loss of data.

curioucity
05-01-04, 04:38 AM
Wait a second.... is pow included in C++ library (math.h, maybe?)? If so, I can get it... but how does it do things anyway (I mean the detail of the operation)?

okinrus
05-01-04, 04:51 PM
Wait a second.... is pow included in C++ library (math.h, maybe?)? If so, I can get it...

Yes, in the c library math.h Some compilers will require you to link in the math library with -lm.


but how does it do things anyway (I mean the detail of the operation)?

Most likely power series or something like that. Visual C++ library uses SIMD extensions 2, so it is possible that it's implemented in hardware somehow.

Nebula
05-06-04, 11:35 PM
"curioucity is right in that you shouldn't use define unless you absolutely have to"

I do have to use #define (part of the assignment requirement; otherwise I would be doing the const thing).

I decided to stop pissing around with the types and declare them as doubles.