asked 168k views
2 votes
Given two int variables distance and speed, write an expression that divides distance by speed using floating point arithmetic, i.e., a fractional result should be produced. (NOTE: Simply write an expression that performs the calculation. Do not assign the result to a variable.)

asked
User Madjardi
by
8.4k points

2 Answers

1 vote

Final answer:

The expression to perform floating-point division of two integers 'distance' and 'speed' is '(float) distance / speed', which casts 'distance' to a float.

Step-by-step explanation:

To divide two integers distance and speed using floating-point arithmetic and produce a fractional result, you cast one or both of the integers to a floating-point type before performing the division. This can be achieved using the following expression:

(float) distance / speed

Here, distance is explicitly cast to a float, which makes the resulting division operation a floating-point division. This is necessary because if both operands are integers, integer division would occur, and the fractional part of the result would be lost.

answered
User Realnsleo
by
8.9k points
3 votes

Final answer:

To divide two integer variables distance and speed using floating point arithmetic, you can cast either distance or speed to a float before performing the division.

Step-by-step explanation:

To perform floating point arithmetic and calculate the average speed given two integer variables distance and speed, you would need to make sure at least one of the operands is a floating point number. This ensures the division does not perform integer division but rather floating point division, yielding a fractional result. The expression would look like this:

static_cast(distance) / speed

Or alternatively, if you'd prefer to specify the type of the speed:

distance / static_cast(speed)

Either of these expressions will convert one of the integers to a float, ensuring that the division operation results in a floating point number, not an integer.

answered
User Lechnerio
by
8.2k points