Given the following fragment that purports to convert from degrees Celsius to degrees Fahrenheit, answer the following questions:
double c = 20;
double f;
f = (9/5) * c + 32.0;
a. What value is assigned to f?
b. Explain what is actually happening, and what the programmer likely
wanted.
c. Rewrite the code as the programmer intended.
The statement executed using a program. The program is follows:
#include <iostream>
int main()
{
//declare and initialise variable
double c = 20;
//declare variable
double f;
//calculate the value of f
f = (9/5) * c + 32.0;
std::cout << "Value of f : "<<f;
return 0;
}
Sample Output:
Value of f : 52
a) The value assigned to f is 52.
b) The term (9/5) is evaluated as integer division because 9 and 5 are integers. The result will be 1 as rounding will take place and digits after decimal will be ignored. This is the reson for incorrect result.
c) The term (9/5) should be replaced with (9.0/5.0). Then it will be evaluated as double division.
Following is the updated program:
#include <iostream>
int main()
{
//declare and initialise variable
double c = 20;
//declare variable
double f;
//calculate the value of f
f = (9.0/5.0) * c + 32.0;
std::cout << "Value of f : "<<f;
return 0;
}
Sample Output:
Value of f : 68