Reputation: 393
I have a question like this: Which of the following is the correct datatype for the variable like this:
a = 23.5
a) float
b) double
c) long double
d) None
According to me, it should be double. Because, if we
float a = 23.5
Then, actually, we are initializing a float variable by a double constant. Am I right saying that it is option b?
Upvotes: 5
Views: 233
Reputation: 573
"It depends on" is the right answer.
There are more options then the three you mention.
Upvotes: 0
Reputation: 122373
It depends on what type you need for a
to be in your program logic, not what type of value it's initialized.
Yes, float a = 23.5;
, there is a conversion from the double
literal 23.5
to the float
variable a
, but it's fine. For instance, to initialize a double
variable to 42.0
, people usually use
double a = 42;
in which 42
is of type int
, instead of the longer
double a = 42.0;
So in my opinion, float
, double
, or long double
can all be considered correct here.
Upvotes: 5
Reputation: 104
You can declare this variable as double, float, or long double.
The difference is in the range of the type.
For example (one possible way):
float- 4 bytes
double - 8 bytes
long double - 12 bytes
You can see more details here: http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/CONCEPT/data_types.html
Upvotes: 1