SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
C++ Basics
Exercise:
Self-test Exercises
Question:19 | ISBN:9780321531346 | Edition: 7

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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
0 0

Discussions

Post the discussion to improve the above solution.