Question:
c++ float double truncationconfusion?
Dry_rubber_Chicken
2012-03-08 13:57:24 UTC
I am new to c++. I know this won't prevent my code from running or anything, but I would like to understand.

I have an example in my book using value such as
float carpet_cost = 7.35; //This IS a float and not a double, right?

I declare this as a float and get a warning about truncation from double.
If I put the
float 7.35f
I get no such warning, but results like a float.

I was under the impression that float would equal say
7.3500001
while a double would be
7.350000000000001.

Why would it even consider initializing that variable as a double(4byte) when I specifically told it to init a float(2byte). Again, this code without the trailing F, warns of a conversion from double to float with a decalred float. Also, if you're feeling generous, is there no Single in C++?



#include "stdafx.h"

using namespace System;

int main(array ^args)
{///Begin main code block
float ii_carpet_price_per_yard = 1.32f;
float ii_room_width = 12.21f;
float ii_room_length = 13.52f;
float ii_room_height = 9.63f;

const int ii_feet_per_yard = 3;

float ii_room_width_yards = ii_room_width / ii_feet_per_yard;
float ii_room_length_yards = ii_room_length / ii_feet_per_yard;
float ii_total_carpet_price = (ii_room_length_yards * ii_room_width_yards) * ii_carpet_price_per_yard;

Console::Write(" - {0} - {1} - {2} -" , ii_total_carpet_price, ii_room_length_yards, ii_room_width_yards);
Console::Read();
return 0; ///Kill it with fire
}///End main code block
Three answers:
John H
2012-03-08 14:01:15 UTC
Your assumptions about sizes of floats and doubles is wrong.



Also, constant literals have a type. That's why you need the f if you really want a float literal and not a double. The default type for floating point literals is double.
sspade30
2012-03-08 15:30:17 UTC
3.4 is a double. That is the default for a literal value with a decimal point. If you want a float, put an f at the end.



float and double sizes can vary by machine and compiler.



EDIT:

and accuracy is not "too the right" of the decimal point. It is approximately 7 digits. The decimal point can be placed anywhere (within the range of the exponent). So, 0.0000000000000000001234567 fits in a float, and so does 1,234,567,000,000,000,000,000,000.00
ison
2016-12-09 02:57:28 UTC
It relies upon what you're doing. The 'flow' form usually demands much less memory. The 'double' form usually can provide extra precision. while you're calling a lot of purposes that require a 'flow', it would make experience which you will carry your data in a 'flow' interior the 1st place. Ditto for 'double'. usually, maximum programmers use 'flow' except there's a particular reason to apply a 'double'. i've got faith this is largely via fact on maximum structures, 'flow' can provide rather larger overall performance.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...