Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

truncation from double to float?

#include <iostream>

using namespace std;

int main(void)
{
    float haha[2];
    float (&ptr)[2] = haha;
    ptr[0] = 0.54;
    ptr[1] = 0.65;

    cout << haha[0] << '\n' << haha[1];
    system("pause");
    return 0;
}

I am currently learning complicated array declarations using primer C++ and in my code here i get warnings saying Warning C4305 '=': truncation from 'double' to 'float' Array for both ptr[0] and ptr[1] for some reason but i don't see doubles anywhere but when i modify the code to

ptr[0] = (float)0.54;
ptr[1] = (float)0.65;

i seem to have no warnings can anyone explain why? Thank you in advance!

like image 789
psrag anvesh Avatar asked Mar 15 '16 16:03

psrag anvesh


People also ask

How do you truncate a double in C++?

trunc() : Truncates a double value after the decimal point and gives the integer part as the result. The return value and the arguments are of the type double. Syntax : double trunc(double x);

What does it mean Cannot convert from double to float?

The issue is that the double type is higher precision than float . You'll lose information when you make that assignment. That's why the compiler doesn't let you do that. It's similar to what happens when you want to do char b = a where a is an int .

How do you truncate a number in C++?

The trunc() function rounds x towards zero and returns the nearest integral value that is not larger in magnitude than x. Simply, the trunc() function truncate the value after decimal and returns the integer part only.


2 Answers

Immediate values, or literals, like 3, 3.14 or "Hello" have types in C++. The type of 3.14 is double, which is larger than float and causes this warning. By "larger" I mean that it can hold values that do not fit into float if converted, at which point the language may behave in an unexpected way.

You may use suffixes to specify what type you want, 3.14F will be float.

Similarly, for integers you have 3U for unsigned and 3L for long and even combinations of those. C++11 features user-defined suffixes as well.

like image 88
ftynse Avatar answered Oct 21 '22 12:10

ftynse


From Standard 2.14.4, Floating literals:

The type of a floating literal is double unless explicitly specified by a suffix. The suffixes f and F specify float, the suffixes l and L specify long double.

Then, floating literals are always double, unless when explicitly specified by a suffix. Casting to float may work too (be careful with numbers which fits in double's size and not in float's), but you should use casting when it is your only option (not this case). In your code just use a suffix (0.54f) and it will be fine.

like image 29
hlscalon Avatar answered Oct 21 '22 12:10

hlscalon