Question

In: Computer Science

PLEASE MAKE THIS TWO DIFFERENT FILES. ONE FOR CLASS (temperature.h) AND ONE FOR temperature.cpp Objective: This...

PLEASE MAKE THIS TWO DIFFERENT FILES. ONE FOR CLASS (temperature.h) AND ONE FOR temperature.cpp

Objective: This assignment will provide further practice with implementing classes.

Task:  For this homework, you will write a class called Temperature, in the files temperature.h and temperature.cpp, for creating and using objects that will store temperatures (like for weather forecasting programs).

This class should be portable, so it should work with any up-to-date C++ compiler.

Program Details and Requirements:

1) An object of type Temperature should represent a temperature in terms of degrees and scale. Degrees should allow decimal precision (so use type double). The three scales possible are Celsius, Fahrenheit, and Kelvin. You may store the scale however you like inside the object, but for any keyboard input or function parameters, scales will come in as type char, where 'C', 'F', 'K' (as well as the lower case versions) are valid options. Your object must always represent a valid temperature -- remember that 0 Kelvin represents the lowest possible temperature in existence (the complete absence of heat). Your object should also store a format setting, to be used for display of temperatures to the screen. There will be more than one possible format. The class features (public interface) should work exactly as specified, regardless of what program might be using Temperature objects.

Note: For purposes of conversions between scales, please remember the following conversion relationships betweeen temperatures:

  • Celsius = (Fahrenheit - 32) X (5/9)
  • (or) Fahrenheit = (Celsius X 9/5) + 32
  • Celsius = Kelvin - 273.15

2) Your Temperature class must provide the following services (i.e. member functions) in its public section. These functions will make up the interface of the Temperature class. Make sure you use function prototypes as specified here. (You may write any other private functions you feel necessary, but the public interface must include all the functionality described here).

  • the constructor(s):
    The Temperature class should have a constructor that allows the user to specify the values for the degrees and scale, using types double and char, respectively. If any of the values would result in an invalid temperature, the constructor should throw out the erroneous information and initialize the object to represent 0 Celsius, by default. Also, you should allow a Temperature object to be declared without specified parameter values, in which case it should initialize to 0 Celsius (the default).

    Examples: These declarations should be legal, and the comment gives the initialized temperature

     Temperature t1;             // initializes to 0 Celsius 
     Temperature t2(23.5, 'F');  // initializes to 23.5 Fahrenheit 
     Temperature t3(12.6, 'Z');  // invalid scale, initializes to 0 Celsius
     Temperature t4(-300, 'c');  // this is below 0 Kelvin, inits to 0 Celsius
     Temperature t5(15, 'k');    // initializes to 15 Kelvin
  • void Input()
    This function should prompt the user to enter a temperature, and then allow the user to input a temperature from the keyboard. User input is expected to be in the format degrees scale, where degrees allows values with decimal precision, and scale is entered as a character. Whenever the user attempts to enter an invalid temperature, the Input function should display an appropriate error message (like "Invalid temperature. Try again: ") and make the user re-enter the whole temperature. A few examples of some good and bad inputs:
     Legal:    43.6 k , 53.5 C , 100 F , -273.15 c
     Illegal:  12.3 q , -5 K , -278 C , -500 F       // last 3 are below absolute zero
    

    You may assume that the user entry will always be of the form:
    D S where D is a numeric value and S is a character

  • void Show()
    This function should simply output the temperature to the screen. There will be more than one possible format for this output, however, and your class will need to store a format setting. The Show function should use the format setting to determine the output. (There will be a member function that allows the setting to be changed). When a Temperature object is created, the format setting should start out at the "Default" setting. The possible formats are shown in the following table:
    Name Format Example Explanation
    Default D S 50.4316 C This will look mostly like the input from the Input function.
    Print the degrees and scale as double and char, with default precision on the degrees, and the scale as an uppercase letter
    Precision-1 D.d S 50.4 C Degrees printed to 1 place after the decimal, fixed format, and scale printed as an uppercase letter. This output will need to make sure to put the output stream BACK to its original format settings when you are done, (so that output from a main program isn't now set to 1 decimal place for the caller, for example). See this notes addendum for more details on this kind of thing
    Long D scale 50.4316 Celsius This display format should show the degrees in default precision, and the scale as the full word "Celsius", "Fahrenheit", or "Kelvin"

  • bool Set(double deg, char s)
    This function should set the temperature to the specified values (the first parameter represents the degrees, the second represents the scale If the resulting temperature is an invalid temperature, the operation should abort (i.e. the existing stored temperature should not be changed). This function should return true for success and false for failure (i.e. invalid temperature sent in).
  • double GetDegrees()
    char GetScale()
    These are "accessor" functions, and they should return the degrees and scale to the caller, respectively.
  • bool SetFormat(char f)
    This function allows the caller to change the format setting. The setting should be adjusted inside the object based on the character code passed in. This means that future uses of the Show function will display in this given format until the format is changed. The valid setting codes that can be passed in are:
     'D' = Default format 
     'P' = Precision-1 format 
     'L' = Long format 
    

    If an invalid setting code is passed in, do not alter the current format setting. This function should return true for successful format change, and false for failure (invalid setting given).

  • bool Convert(char sc)
    This function should convert the current temperature (i.e. the calling object) so that it is now represented in the new scale given in the parameter. You'll need to use the temperature conversion factors for this. If the scale provided is invalid, abort the operation and do not change the current temperature. Otherwise, convert the temperature to the new scale, so that it is equivalent to the previous representation. Return true for success, false for failure (i.e. invalid scale). Examples:
      Temperature t1(68.9, 'F');            // 68.9 Fahrenheit  
    
      t1.Convert('T');              // invalid scale, no change.  Returns false
      t1.Convert('c');              // t1 is now 20.5 Celsius
      t1.Convert('K');              // t1 is now 293.65 Kelvin
    
  • int Compare(const Temperature& d)
    This function should compare two Temperature objects (the calling object and the parameter), and should return: -1 if the calling object is the lower temperature, 0 if the objects represent the same temperature, and 1 if the parameter object is the lower temperature. The function should not change either original object. Example:
      Temperature t1(0, 'C');               // 0 Celsius
      Temperature t2(31.5, 'F');            // 31.5 Fahrenheit
    
      t1.Compare(t2);               // returns 1  (since t2 comes first)
      t2.Compare(t1);               // returns -1 (calling object is t2, comes first)
    

3) General Requirements:

  • all member data of the Temperature class must be private.
  • The const qualifier must be used on any member functions where it is appropriate
  • the only libraries that may be used in these class files are <iostream>, <iomanip>, <cctype>, and <string>. Note that you may use the string class to store the words like "Celsius", etc. Although this class can easily be written without using class string.
  • Do not use langauge or library features that are C++11-only
  • You only need to do error-checking that is specified in the descriptions above. If something is not specified (e.g. user entering a letter where a number is expected), you may assume that part of the input will be appropriate. You must always maintain a valid temperature object (in all your functions), but for keyboard input, you may assume that if you ask for a double, you will get a number (not words), for example.
  • user input and/or screen output should only be done where described (i.e. do not add in extraneous input/output).
  • no global variables, other than constants

Testing Your Class:

You will need to test your class, which means you will need to write one or more main programs that will call upon the functionality (i.e. the public member functions) of the class and exercise all of the different cases for each function. You do not need to turn any test programs in, but you should write them to verify your class' features.

Here is the beginning of a sample test program to get you started:

// sample.cpp -- sample test program starter for Temperature class
/////////////////////////////////////////////////////////

#include <iostream>
#include "temperature.h"

using namespace std;

int main()
{
   Temperature t1;              // should default to 0 Celsius
   Temperature t2(34.5, 'F');  // should init to 34.5 Fahrenheit 

   // display dates to the screen
   cout << "\nTemperature t1 is: ";
   t1.Show();                   
   cout << "\nTemperature t2 is: ";
   t2.Show();

   t1.Input();                  // Allow user to enter a temperature for t1
   cout << "\nTemperature t1 is: ";
   t1.Show();                   
   
   t1.SetFormat('L');           // change format of t1 to "Long" format
   cout << "\nTemperature t1 is: ";
   t1.Show();                   

   // and so on.  Add your own tests to fully test the class' 
   //   functionality.
}

Solutions

Expert Solution

Temperature.h

//==============================================

#ifndef TEMPERATURE_H
#define TEMPERATURE_H
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;

class Temperature
{
private:
   double degree;
   char scale;
   char format;
public:
   Temperature();
   Temperature(double deg, char sc);
   void Input();
   void Show() const;
   bool Set(double deg, char s);
   double GetDegrees() const;
   char GetScale() const;
   bool SetFormat(char f) ;
   bool Convert(char sc) ;
   int Compare(const Temperature& d) const;
};

#endif

//==============================================

Temperature.cpp

//==============================================

#ifndef TEMPERATURE_H
#include"temperature.h"
#endif

Temperature::Temperature()
{
   degree = 0;
   scale = 'C';
   format = 'D';
}
Temperature::Temperature(double deg, char s)
{
   format = 'D';
   // check for valid scale input
   if (!(s == 'F' || s == 'K' || s == 'C' || s == 'f' || s == 'k' || s == 'c'))
   {
       cout << "\nInvalid scale" ;
       degree = 0.0;
       scale = 'C';
   }
   else
   {
       // check if scale is fehrenheit
       if (s == 'F' || s=='f')
       {
           // conversion of fehrenheit to celsius then celsius to kelvin
           double in_kalvin = ((deg - 32) * 5) / 9.0 + 273.15;
           // if input is not valid degree value
           if (in_kalvin < 0.0)
           {
               cout << "\nThis is below 0 Kelvin" ;
               degree = 0;
               scale = 'C';
           }
           else
           {
               degree = deg;
               //comversion to capital letter
               if (s >= 'a' && s <= 'z')
               {
                   scale = s - 'a' + 'A';
               }
               else scale = s;
           }
       }
       // check if scale is kelvin and degree is invalid
       // or scale is celsius and degree is less than -273.155 which is less than 0 in kelvin
       if (((s == 'K' || s=='k') && deg < 0) || ((s == 'C'|| s=='c') && deg < -273.15))
       {
           cout << "\nThis is below 0 Kelvin";
           degree = 0;
           scale = 'C';
       }
       else
       {
           degree = deg;
           //comversion to capital letter
           if (s >= 'a' && s <= 'z')
           {
               scale = s - 'a' + 'A';
           }
           else scale = s;
       }
   }
}
void Temperature::Input()
{
   double deg;
   char s;
   bool flag = 1; // check for not valid input
   while (flag)
   {
       cout << "\nPlease provide temperature: ";
       cin >> deg >> s;
       // check for valid scale input
       if (!(s == 'F' || s == 'K' || s == 'C' || s == 'f' || s == 'k' || s == 'c'))
       {
           cout << "Invalid scale in Temprature, please try again ";
       }
       else
       {
           // check if scale is fehrenheit
           if (s == 'F' || s == 'f')
           {
               // conversion of fehrenheit to celsius then celsius to kelvin
               double in_kalvin = ((deg - 32) * 5) / 9.0 + 273.15;
               // if input is not valid degree value
               if (in_kalvin < 0.0)
               {
                   cout << "Invalid degree in Temprature, please try again";
               }
               else
               {
                   degree = deg;
                   //comversion to capital letter
                   if (s >= 'a' && s <= 'z')
                   {
                       scale = s - 'a' + 'A';
                   }
                   else scale = s;
                   flag = 0;
               }
           }
           // check if scale is kelvin and degree is invalid
           // or scale is celsius and degree is less than -273.155 which is less than 0 in kelvin
           if (((s == 'K' || s == 'k') && deg < 0) || ((s == 'C' || s == 'c') && deg < -273.15))
           {
               cout << "Invalid degree in Temprature, please try again";
           }
           else
           {
               degree = deg;
               //comversion to capital letter
               if (s >= 'a' && s <= 'z')
               {
                   scale = s - 'a' + 'A';
               }
               else scale = s;
               flag = 0;
           }
       }
   }

}
// print temprature also tested getter member function
void Temperature::Show() const
{
   if (format == 'D')
   {
       cout << GetDegrees() << " " << GetScale() ;
   }
   else if (format == 'L')
   {
       string sc;   // creating full name string
       if (GetScale() == 'C') sc = "Celsius";
       else if (GetScale() == 'F') sc = "Fahrenheit";
       else sc = "Kelvin";
       cout << GetDegrees() << " " << sc ;
   }
   else
   {
       cout << fixed<<setprecision(1) << GetDegrees() << " " << GetScale() ;
   }
}
// set degree and scale if valid
bool Temperature::Set(double deg, char s)
{
   // check for valid scale input
   if (!(s == 'F' || s == 'K' || s == 'C' || s == 'f' || s == 'k' || s == 'c'))
   {
       return false;
   }
   else
   {
       // check if scale is fehrenheit
       if (s == 'F' || s == 'f')
       {
           // conversion of fehrenheit to celsius then celsius to kelvin
           double in_kalvin = ((deg - 32) * 5) / 9.0 + 273.15;
           // if input is not valid degree value
           if (in_kalvin < 0.0)
           {
               return false;
           }
           else
           {
               degree = deg;
               //comversion to capital letter
               if (s >= 'a' && s <= 'z')
               {
                   scale = s - 'a' + 'A';
               }
               else scale = s;
               return true;
           }
       }
       // check if scale is kelvin and degree is invalid
       // or scale is celsius and degree is less than -273.155 which is less than 0 in kelvin
       else if (((s == 'K' || s == 'k') && deg < 0) || ((s == 'C' || s == 'c') && deg < -273.15))
       {
           return false;
       }
       else
       {
           degree = deg;
           //comversion to capital letter
           if (s >= 'a' && s <= 'z')
           {
               scale = s - 'a' + 'A';
           }
           else scale = s;
           return true;
       }
   }
}
// return degree of tempreture
double Temperature::GetDegrees() const
{
   return degree;
}
// return scale of tempreture
char Temperature::GetScale() const
{
   return scale;
}
// update format if input is valid format
bool Temperature::SetFormat(char f)
{
   //check if valid formate is input
   if (f == 'D' || f == 'P' || f == 'L')
   {
       format = f;
       return true;
   }
   //check if valid formate is input in small letter if allowed
   /*
   if (f == 'd' || f == 'p' || f == 'l')
   {
       format = f -'a' + 'A';
       return false;
   }
   */
   // not valid input
   return false;
}
bool Temperature::Convert(char sc)
{
   char c_sc = sc; // convert to capital scale
   if (sc >= 'a' && sc <= 'z') c_sc = sc - 'a' + 'A';

   // check for valid scale input ( capital or small letter)
   if (!(c_sc == 'F' || c_sc == 'K' || c_sc == 'C' ))
   {
       return false;
   }
   // convert degree accordint to present scale and required scale
   if (c_sc == 'F' && scale == 'C')
   {
       degree = ((degree * 9) / 5.0) + 32;
   }
   else if (c_sc == 'F' && scale == 'K')
   {
       // first conversion to celsius then converted to fehrenheit
       degree = (((degree-273.15) * 9) / 5.0) + 32;
   }
   else if (c_sc == 'C' && scale == 'F')
   {
       degree = ((degree - 32) * 5) / 9.0;
   }
   else if (c_sc == 'C' && scale == 'K')
   {
       degree = degree - 273.15;
   }
   else if (c_sc == 'K' && scale == 'F')
   {
       // first converted to celsius than converted to kelvin
       degree = ((degree - 32) * 5) / 9.0 + 273.15;
   }
   else if (c_sc == 'K' && scale == 'C')
   {
       degree = degree + 273.15;
   }
   //update scale and return true;
   scale = c_sc;
   return true;
}
// compare degree to calling object and input object
int Temperature::Compare(const Temperature& d) const
{
   double degr_d = d.GetDegrees();
   char scale_d = d.GetScale();
   // if scale of d is not matching with calling object
   // convert degree to same scale locally;
   if (scale == 'C' && scale_d == 'F')
   {
       degr_d = ((degr_d - 32) * 5) / 9.0;
   }
   else if (scale == 'C' && scale_d == 'K')
   {
       degr_d = degr_d - 273.15;
   }
   else if (scale == 'F' && scale_d == 'C')
   {
       degr_d = ((degr_d *9)/5.0) + 32;
   }
   else if (scale == 'F' && scale_d == 'K')
   {
       // first convert to celsius then to fehrenhit
       degr_d = (((degr_d - 273.15) * 9) / 5.0) + 32;
   }
   else if (scale == 'K' && scale_d == 'F')
   {
       // first convert to celsius then to kelvin
       degr_d = ((degr_d - 32) * 5) / 9.0 + 273.15;
   }
   else if (scale == 'K' && scale_d == 'C')
   {
       degr_d = degr_d + 273.15;
   }

   // if calling object is having higher degree
   if (degree > degr_d) return 1;
   // if calling object is having less degree
   if (degree < degr_d) return -1;
   // both are having same tempraturee
   return 0;
}

//=====================================================

main.cpp

//=====================================================

#include <iostream>
#include "temperature.h"

using namespace std;

int main()
{
   Temperature t1;              // should default to 0 Celsius
   Temperature t2(34.5, 'F'); // should init to 34.5 Fahrenheit
   Temperature t3(-5, 'K'); // invalid degree in kalvin
   Temperature t4(-274, 'C'); // invalid degree in calsius
   Temperature t5(10, 'T'); // invalid scale;

   // display temprature to the screen
   cout << "\nTemperature t1 is: ";
   t1.Show();
   cout << "\nTemperature t2 is: ";
   t2.Show();
   cout << "\nTemperature t3 is: ";
   t3.Show();
   cout << "\nTemperature t4 is: ";
   t4.Show();
   cout << "\nTemperature t5 is: ";
   t5.Show();

   t1.Input();                  // Allow user to enter a temperature for t1
   cout << "\nTemperature t1 is: ";
   t1.Show();

   t1.SetFormat('L');           // change format of t1 to "Long" format
   cout << "\nTemperature t1 is: ";
   t1.Show();

   t2.SetFormat('P');           // change format of t2 to "presicion-1" format
   cout << "\nTemperature t2 is: ";
   t2.Show();

   bool t3_set = t3.Set(45, 'c');   // set temperatur of t3
   if (t3_set)cout << "\nSuccessfully set temperature of t3";
   else cout << "\nUnsuccessfully to set temperature of t3";
   t3.Show();
   cout << "\nTemperature t4 is: ";
  
   bool t4_set = t4.Set(45, 't'); // failed to set temperature
   if (t4_set)cout << "\nSuccessfully set temperature of t4";
   else cout << "\nUnsuccessfully to set temperature of t4";
   t4.Show();
   cout << "\nTemperature t5 is: ";

   bool t5_convert = t5.Convert('K'); // convert t5 to kelvin
   if (t5_convert)cout << "\nSuccessfully convert temperature of t5";
   else cout << "\nUnsuccessfully to convert temperature of t5";
   cout << "\nTemperature t5 is: ";
   t5.Show();

   bool t4_convert = t4.Convert('p'); // failed convert of t4
   if (t4_convert)cout << "\nSuccessfully convert temperature of t4";
   else cout << "\nUnsuccessfully to convert temperature of t4";
   cout << "\nTemperature t4 is: ";
   t4.Show();

   int t1_t2 = t1.Compare(t2);
   if (t1_t2 == 1) cout << "\nTemperature t1 is greater than temperature t2";
   else if (t1_t2 == -1 )cout << "\nTemperature t2 is greater than temperature t1";
   else cout << "\nBoth temperature t1 and t2 are equal";

   // and so on. Add your own tests to fully test the class'
   //   functionality.
   cout << "\n";
   system("pause");
   return 0;
}

//=====================================================

output 1:case t1<t2

output 2: case t1 == t2

output 3: case t1> t2

Note: I have tried my best to test all member function.


Related Solutions

Basic Unix Commands Objective: The objective of this lab is to work with files of UNIX...
Basic Unix Commands Objective: The objective of this lab is to work with files of UNIX file system. Procedure: 1. OpenyourUnixshellandtrythesecommands: Ø Create a new file and add some text in it vcat > filename Ø View a file vcat /etc/passwd vmore /etc/passwd vmore filename Ø Copy file, making file2 vcp file1 file2 Ø Move/rename file1 as file2 vmv file1 file2 Ø Delete file1 as file2 vrm file //Deletefile //Double-checkfirst vrm -i file Ø Counts the lines, words, characters in...
Objectives: Use class inheritance to create new classes. Separate class definition and implementation in different files....
Objectives: Use class inheritance to create new classes. Separate class definition and implementation in different files. Use include guard in class header files to avoid multiple inclusion of a header. Tasks: In our lecture, we wrote a program that defines and implements a class Rectangle. The source code can be found on Blackboard > Course Content > Classes and Objects > Demo Program 2: class Rectangle in three files. In this lab, we will use class inheritance to write a...
PLEASE DO IN C# Warehouse Inventories Objective: Work with multiple objects and review reading data files....
PLEASE DO IN C# Warehouse Inventories Objective: Work with multiple objects and review reading data files. Description: A wholesale distributor has six warehouses (Atlanta, Baltimore, Chicago, Denver, Ely and Fargo) and sells five different items (identified by part number: 102, 215, 410, 525 and 711). Each warehouse may stock any or all of the five items. The company buys and sells these items constantly. Company transaction records contain a transaction code (‘P’ for a purchase or ‘S’ for a sale)...
Objective You are given a partial implementation of one header file, GildedRose.h. Item is a class...
Objective You are given a partial implementation of one header file, GildedRose.h. Item is a class that holds the information for each item for the inn. GildedRose is a class that holds an internal listing of many Item objects. This inventory should hold at least 10 items. For this you can use arrays, the std::array class, or even the vector class. Complete the implementation of these classes, adding public/private member variables and functions as needed. You should choose an appropriate...
C++ Create an ArrayBag template class from scratch. This will require you to create two files:...
C++ Create an ArrayBag template class from scratch. This will require you to create two files: ArrayBag.hpp for the interface and ArrayBag.cpp for the implementation. The ArrayBag class must contain the following protected members: static const int DEFAULT_CAPACITY = 200; // max size of items_ ItemType items_[DEFAULT_CAPACITY]; // items in the array bag int item_count_; // Current count of items in bag /** @param target to be found in items_ @return either the index target in the array items_ or...
In Java: (1) Create two files to submit: ItemToBuy.java - Class definition ShoppingCartDriver.java - Contains main()...
In Java: (1) Create two files to submit: ItemToBuy.java - Class definition ShoppingCartDriver.java - Contains main() method Build the ItemToBuy class with the following specifications: Private fields String itemName - Initialized in the nor-arg constructor to "none" int itemPrice - Initialized in default constructor to 0 int itemQuantity - Initialized in default constructor to 0 No-arg Constructor (set the String instance field to "none") Public member methods (mutators & accessors) setName() & getName() setPrice() & getPrice() setQuantity() & getQuantity() toString()...
Please do both questions in MASM and complete these two in two separate files. 3. Summing...
Please do both questions in MASM and complete these two in two separate files. 3. Summing the Gaps between Array Values Write a program with an indexed addressing that calculates the sum of all the gaps between successive array elements. The array elements are doublewords, sequenced in nonde- creasing order. So, for example, the array {0, 2, 5, 9, 10} has gaps of 2, 3, 4, and 1, whose sum equals 10.      4. Copying a Word Array to a DoubleWord...
Edit question Write a program that merges two files as follows. The two files are in...
Edit question Write a program that merges two files as follows. The two files are in the docsharing which you can download it. One file will contain usernames(usernames.txt):foster001smith023nyuyen002...The other file will contain passwords(passwords.txt):x34rdf3ep43e4rddw32eds22...The program should create a third file matching username and passwords(usernamesPasswords.txt):foster001x34rdf3esmith023p43e4rddnyuyen002w32eds22......Give the user of your programs the option of displaying you output file. CAN ANYONE SOLVE THIS IN C
Objective Work with strings Work with files Work with formatted output This program will display a...
Objective Work with strings Work with files Work with formatted output This program will display a very basic handling of transactions for a checking account. The program will read in a data file with all the past transactions. Use FileUtil.selectOpenFile or input() to get a file name from the user. The format of the file will be very basic, just a date (as a string in the format of MM/DD), a single letter which indicates the type of transaction (‘B’...
1.         Please describe the two factors that make social, local, and mobile marketing different from traditional...
1.         Please describe the two factors that make social, local, and mobile marketing different from traditional online marketing. 2.         Why are social, mobile, and local marketing efforts interconnected? 3.         Why is the connection between social, mobile, and local marketing important to marketers? 4.         What are the objectives of social marketing?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT