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:
Defining Classes
Exercise:
Self-test Exercises
Question:12 | ISBN:9780321531346 | Edition: 7

Question

Given the following class definition, write an appropriate definition for

the member function set:

class Temperature

{

public:

void set(double new_degrees, char new_scale);

//Sets the member variables to the values given as

//arguments.

double degrees;

char scale; //'F' for Fahrenheit or 'C' for Celsius.

};

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

The definition for the set member function of the Temperature class:

PROGRAM CODE:

#include <stdexcept> // Include this header to use std::invalid_argument

class Temperature
{
public:
    void set(double new_degrees, char new_scale)
    {
        // Check if the scale is valid ('F' or 'C')
        if (new_scale != 'F' && new_scale != 'C')
        {
            throw std::invalid_argument("Invalid scale. Use 'F' for Fahrenheit or 'C' for Celsius.");
        }

        // Assign the new values to the member variables
        degrees = new_degrees;
        scale = new_scale;
    }

    double degrees;
    char scale; // 'F' for Fahrenheit or 'C' for Celsius.
};
  • The set member function takes two arguments: new_degrees (a double representing the new temperature value) and new_scale (a char representing the scale, which can be either 'F' for Fahrenheit or 'C' for Celsius).
  • In the set function, we first check if the provided scale is valid ('F' or 'C'). If it is not valid, we throw an exception using std::invalid_argument to indicate that an invalid scale was provided. Otherwise, we assign the new_degrees and new_scale values to the member variables degrees and scale, respectively.

This set member function allows you to set the temperature and its scale for an instance of the Temperature class. For example:

Temperature t;
t.set(75.0, 'F'); // Sets the temperature to 75.0 degrees Fahrenheit

 

0 0

Discussions

Post the discussion to improve the above solution.