user3797829
user3797829

Reputation: 393

Correct datatype for a variable

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

Answers (3)

Jakub
Jakub

Reputation: 573

"It depends on" is the right answer.

There are more options then the three you mention.

  • If yo can safely assume that your numbers are either an integer, or an integer +1/2 then storing 2 * i in an integral type may be the right choice.
  • Another option is a rational number. There are libraries out there for this.

Upvotes: 0

Yu Hao
Yu Hao

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

Asaf Kahlon
Asaf Kahlon

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

Related Questions