1.11M Members

warning C4305: '=' : truncation from 'double' to 'float'

 
0
 

Hi guys ,

In Visual Studio 2005 I compiled the following code

int main()
{
	float a;
	a=0.1; 

	if(a<0.1)
	{ 
		printf("C\n");
	}
	else
	{
		printf("C++\n");
	}
}

I was very surprised when I saw the output C++ .
I got the warning C4305 :" '=' : truncation from 'double' to 'float' " , I searched the web but couldn't find some answers .

I don't understand what's wrong with assigning the value 0.1 to a float variable .

Thank you

 
1
 

>I don't understand what's wrong with assigning the value 0.1 to a float variable .

There's nothing wrong with it, the compiler is warning you that you are trying to assign a double to a float.
A literal 0.1 is a double in your compiler.
Do a test. Add these printf(s) to your snippet.

printf( "sizeof of 0.1 = %d bytes\n", sizeof( 0.1 ) );
printf( "sizeof of float = %d bytes\n", sizeof( float ) );

The result will be clear to you.

[Edit]: Some extra.

In fact even

if( a <= 0.1 )

will evaluate to FALSE because float != double. However

if( a <= ( float ) 0.1 )

will evaluate to TRUE

 
0
 

This helped a lot , thanks Aia . You're great .

Question Answered as of 6 Years Ago by Aia
 
0
 

Very interesting case
If you change 0.1 to 0.5 you will not get warning message

int main()
{
    float a;
    a=0.5; 

    if(a<0.5)
    { 
        printf("C\n");
    }
    else
    {
        printf("C++\n");
    }
}
 
1
 

You could also initialize a float using

float a = 0.1f;

The f tells the compiler that its a float.

 
0
 

On related topic, you may find this thread interesting.
ArkM has explained floating pont conversions pretty well.

 
0
 

Oops, replied to a solved thread. :icon_cheesygrin:

 
-1
 

I know that this thread is a year old but I just hod to comment.

I am just trying to learn C++ on my owna nd picked up a book. One of the examples in the book for building your own structures is as follows:

//structur.cpp -- a simple sructure
#include<iostream>
struct inflatable //structure declaration
{
	char name[20];
	float volume;
	double price;
};

int main()
{
	using namespace std;
	inflatable guest =
	{
		"Glorious Gloria",  //name value
		1.88,  //volume value
		29.99  //price value
	};  //guest is a structure variable of the type inflatable
// its initialized to the indicated values

this gave me the exact same compile errors posted here. So I googled the error and was brought here. From this thread I attempted to change the code by adding the "f" to show the value is a float and it worked! Thanks guys!

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article