serious doubt

P

prajwalps97

void main()
{

float a=1.9;
if(a<1.9)
cout<<"c";
else
cout<<"c++";
getch();
}


o/p is

c. how is this..
 
P

Phlip

prajwalps97 said:
void main()

'void main' will make your favorite radio station switch to JackFM in mid
drive-time. Use 'int main'.
{

float a=1.9;
if(a<1.9)
cout<<"c";
else
cout<<"c++";
getch();
}


o/p is

c. how is this..

How is because 1.9 is not precise. A floating-point number is always (deep
breath) a binary representation of a mantissa and an exponent, using a fixed
number of bits for each. There are never enough bits for most fractional
numbers; even 0.1 is frequently very imprecise. Figure out for yourself what
fractional power of 2 is nearest to 0.1 in 64 bits.

Hence never expect two floats to exactly compare. If your app really really
needs a precise 1.9, then multiply your basic unit by 10 and compare 19 as
integers.
 
M

Markus Moll

Hi

void main()
{

float a=1.9;
if(a<1.9)
cout<<"c";
else
cout<<"c++";
getch();
}


o/p is

c. how is this..

BTW: I think it is generally considered polite to use at least one complete
sentence when interacting with other people. ;-)

Your piece of code does not compile on my computer:

|1: error: ‘::main’ must return ‘int’
| In function ‘int main()’:
|6: error: ‘cout’ was not declared in this scope
|8: error: ‘cout’ was not declared in this scope
|9: error: ‘getch’ was not declared in this scope

Besides fixing those errors, you should have a look at
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.17
It would be a good idea to also read the rest of the FAQ.

hth
Markus
 
V

Victor Bazarov

void main()
{

float a=1.9;
if(a<1.9)
cout<<"c";
else
cout<<"c++";
getch();
}


o/p is

c. how is this..

Besides the obvious errors pointed out by Markus, you're
comparing a float and a double. Try

float a = 1.9f;
if (a < 1.9f)

V
 
P

Pete Becker

void main()
{

float a=1.9;
if(a<1.9)
cout<<"c";
else
cout<<"c++";
getch();
}

The type of a is float, and it's initialized with a double value 1.9.
The extra bits in the initializer are discarded to convert that double
value to a float. In the comparison, 1.9 is a double, not a float, so
the value of a is promoted to double by appending trailing zeros. The
resulting value is not equal to the double 1.9. If you change the value
in the comparison to 1.9f it will work much better.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top