171k views
4 votes
The formula for converting a Fahrenheit temperature to Centigrade is 5/9(F - 32). What is wrong with writing it in C++ as C = 5/9 * (F - 32) assuming that C and F are both declared as doubles, and F has a valid value.

1 Answer

3 votes

Final answer:

The problem with the C++ code C = 5/9 * (F - 32) is that it uses integer division since both 5 and 9 are integers. This means the fraction 5/9 would evaluate to 0. To correct it, use a floating-point literal like 5.0/9.

Step-by-step explanation:

The student asked what is wrong with the C++ expression C = 5/9 * (F - 32) for converting Fahrenheit to Celsius, when C and F are both declared as doubles.

The mistake in this C++ expression lies in the division 5/9. In C++, if both operands are integers, the result of the division will also be an integer and hence it will result in integer division. Since 5/9 is less than one, it would truncate to zero. To fix this, at least one of the operands should be a floating-point number (double or float).

For instance, you should write the formula as C = 5.0/9 * (F - 32) to ensure that the division is done in floating-point arithmetic.

The formula for converting a temperature from Fahrenheit to Celsius is C = (5/9) * (F - 32). In C++, if you write C = 5/9 * (F - 32), it will give you an incorrect answer because the division operation will truncate the fractional part due to integer division. To fix this, you need to make sure that either 5 or 9 is represented as a floating-point number. You can do this by writing C = 5.0/9 * (F - 32) or C = 5/9.0 * (F - 32).

User Lhunath
by
7.4k points