Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

c++ - Does one double promote every int in the equation to double?

Does the presence of one floating-point data type (e.g. double) ensure that all +, -, *, /, %, etc math operations assume double operands?

If the story is more complicated than that, is there a resource that describes these rules? Should I not ask such questions and always explicitly cast int to double when the result of the equation is double. Here are some equations I'm thinking about. I purposefully did not compile and run then on my system, since this is the type of thing that could be compiler dependent.

int a(1), b(2), c(3);
double d(4.);
double result1 = a + b/d + c; // equal to 4 or to 4.5?
double result2 = (a + b)/d + c; // equal to 3 or to 3.75?    
double result3 = a/b + d; // equal to 4 or to 4.5?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I purposefully did not compile and run then on my system, since this is the type of thing that could be compiler dependent.

This is not compiler dependent. C++ clearly defines the order of these operations and how they are converted.

How the conversion happens is dependent on the order of operations.

double result1 = a + b / d + c; // equal to 4 or to 4.5?

In this example, the division happens first. Because this is an int divided by a double, the compiler handles this by converting the int into a double. Thus, the result of b / d is a double.

The next thing that C++ does is add a to the result of b / d. This is an int added to a double, so it converts the int to a double and adds, resulting in a double. The same thing happens with c.

double result3 = a / b + d; // equal to 4 or to 4.5?

In this example, division is handled first. a and b are both ints, so no conversion is done. The result of a / b is of type int and is 0.

Then, the result of this is added to d. This is an int plus a double, so C++ converts the int to a double, and the result is a double.

Even though a double is present in this expression, a / b is evaluated first, and the double means nothing until execution reaches the double. Therefore, integer division occurs.

I find promotion and conversion rules pretty complex. Usually integer-like numbers (short, int, long) are promoted to floating-point equivalents (float, double). But things are complicated by size differences and sign.

See this question for specifics about conversion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...