Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 136,460 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,776 people online right now. Registration is fast and FREE... Join Now!




C++ Question

 
Reply to this topicStart new topic

C++ Question, Did I do this right?

rayjred
2 Aug, 2008 - 12:35 PM
Post #1

New D.I.C Head
*

Joined: 19 Jul, 2008
Posts: 10

Here is my homework question, just looking to see if I'm on the right track and may be some pointers:

A University needs a program to calculate residence fees for its students. The fees are charged at a weekly rate that depends on the type of hall the student is going reside in. The fees also depend on whether or not a student opts to have high speed internet access and or cable television available in the room. The university has 3 halls with the following weekly rates:
Weekly Rates
Hall Room Internet TV
Brown 800.00 50 20
Carlton 1000.00 50 20
Dalton 1500.00 80 20

Write a program that will prompt the user for the following:
Type of Hall?
Number of weeks of stay
Whether or not Internet access is required
Whether or not TV access is required

The program will multiply the effective rate by the number of weeks stay to come up with a total charge.


Here is what I coded:

CODE

// This program calculates residence fees for its students,
// internet access rates, and tv access rates.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    const double internet = 50 || 80;
    const double tv = 20;
    int student_count;
    char hall_type;
    double    weekly_room_rate,
            internet_access_rate,
            tv_access_rate,
            price_hall,
            number_of_weeks,
            room_rate,
            total_price,
            total;

    cout << setprecision(2)
         << setiosflags(ios::fixed)
         << setiosflags(ios::showpoint);
    
        // Display banner

    cout << "This program calculates residence fees for its students."
         << endl << endl;
    cout << "At each prompt, enter the requested data.";

    // Obtain input data

    cout << endl << endl << "Enter the weekly room rate:";
    cin >> weekly_room_rate;
    cout << endl << "Enter the number of weeks:";
    cin >> number_of_weeks;
    cout << endl << "Enter internet access rate (Yes or No):";
    cin.get();                        // Discard the \n
    internet_access_rate = cin.get();
    cout << endl << "Enter tv access rate (Yes or No):";
    cin.get();                        // Discard the \n
    tv_access_rate = cin.get();

        //Calculate internet access

    if (internet_access_rate == 'Yes')
    {
        total = weekly_room_rate + internet_access_rate;
    }
    else
    {
        total = weekly_room_rate;
    }
        //Calculate tv access

    if (tv_access_rate == 'Yes')
    {
        total = weekly_room_rate + tv_access_rate;
    }
    else
    {
        total = weekly_room_rate;
    }
    //Calculate total

    total = number_of_weeks * weekly_room_rate;

    return 0;

}


Thanks in advance.
User is offlineProfile CardPM
+Quote Post

gabehabe
RE: C++ Question
2 Aug, 2008 - 01:27 PM
Post #2

Donkey DIC
Group Icon

Joined: 6 Feb, 2008
Posts: 5,539



Thanked: 98 times
Dream Kudos: 2650
Expert In: ruling the world.

My Contributions
There were a few things wrong with it, nothing huge, but you could keep it pretty damn neat.

I'm bored so I rewrote it quickly, here it is:
cpp
// This program calculates residence fees for its students,
// internet access rates, and tv access rates.

#include <iostream>

using namespace std;

int main()
{
// set the constant variables, how much internet/tv costs per week
const int internet_access_rate = 10, tv_access_rate = 15;
// variables that need to be inputted
double weekly_room_rate, weeks, total;
char internet, tv; // y/n character to ask if user has tv/internet access


cout << "This program calculates residence fees for its students."
<< endl << endl
<< "At each prompt, enter the requested data.";

// Obtain input data

cout << endl << endl << "Enter the weekly room rate:";
cin >> weekly_room_rate;
cout << endl << "Enter the number of weeks:";
cin >> weeks;
cout << endl << "Do you have internet access? (Y/N):";
cin.get(); // Discard the \n
internet = cin.get();
cout << endl << "Do you have TV access? (Y/N):";
cin.get(); // Discard the \n
tv = cin.get();

total = weekly_room_rate * weeks; // give total a base amount

// don't forget to check for lower case!

//Calculate internet access
if (internet == 'Y' || internet == 'y')
total += weeks * internet_access_rate;

//Calculate tv access
if (tv == 'Y' || tv == 'y')
total += weeks * tv_access_rate;


cout << "Total cost: $" << total;

cin.get (); // pause
return EXIT_SUCCESS;
}

Feel free to ask any questions.

[Was this post helpful?] wink.gif
User is offlineProfile CardPM
+Quote Post

jwwicks
RE: C++ Question
2 Aug, 2008 - 02:07 PM
Post #3

D.I.C Head
Group Icon

Joined: 31 Jul, 2008
Posts: 59



Thanked: 6 times
Dream Kudos: 200
My Contributions
Hello rayjred,


QUOTE(rayjred @ 2 Aug, 2008 - 12:35 PM) *
Here is my homework question, just looking to see if I'm on the right track and may be some pointers:

Weekly Rates
Hall Room Internet TV
Brown 800.00 50 20
Carlton 1000.00 50 20
Dalton 1500.00 80 20

Write a program that will prompt the user for the following:
Type of Hall?
Number of weeks of stay
Whether or not Internet access is required
Whether or not TV access is required

cpp
 
cout << endl << endl << "Enter the weekly room rate:";
cin >> weekly_room_rate;




According to the specification you posted you don't need to prompt for the weekly rate. It's a constant based on the Hall the user wants. You'll need to prompt for that. You should probably code something like...

cpp

const double BROWN_HALL_ROOMRATE = 800.00;
const double CARLTON_HALL_ROOMRATE = 1000.00;
const double DALTON_HALL_ROOMRATE = 1500.00;

const double BROWN_HALL_TVRATE = 50.00;
// etc...


And instead of get, use getline though if you just want to prompt for yes or no the whole word yes isn't really needed. Just use Yy or Nn or even simpler 0 and 1.

I'm assuming the data isn't going to be read from a file since the spec didn't mention this. But you could store the data read it into a vector of structures. Probably a little beyond the scope of the assignment at this point though.

When ever I do user input I create a couple of functions that pair up in a do while loop. Like the following...

cpp


do{
choice = get_choice("Press 1 to continue entering data or 0 to quit: ");
}while(!is_valid_choice( choice, 0, 1));

/////////////////////////
/// \fn get_choice( const string& prompt )
/// \brief Check to see if user wants to continue
///
/// \b SideEffects: None\n
/// \b Output: Prompts user to continue program\n
///
/// \return integer of choice entered by user
/////////////////////////
int get_choice( const string& prompt )
{

int ret_val =-1;
stringstream ioConv;

ioConv << get_string(prompt, 1024);
if(ioConv)
ioConv >> ret_val;

return ret_val;
}


/////////////////////////
/// \fn is_valid_choice( int val, size_t min, size_t max )
/// \brief Checks for valid entry for menu
///
/// \b SideEffects : None\n
/// \b Output : Displays an error message if an invalid choice is passed \n
///
/// \param val - Current choice from menu
/// \param min - minimum acceptable value
/// \param max - maximum acceptable value
///
/// \return boolean true if choice is valid and false otherwise
////////////////////////
bool is_valid_choice( unsigned int val, size_t min, size_t max )
{
bool ret_val = false;

if( val >= min && val <= max )
{
ret_val = true;
}

if(!ret_val){
cout << "Error: Invalid choice " << val << " selected." << endl;
}

return ret_val;
}


/////////////////////////
/// \fn get_string( const string& prompt, int maxSize )
/// \brief Gets a user entered string
///
/// \b SideEffects: None\n
/// \b Output: Prompts user to enter in string data\n
///
/// \param prompt - Display string that tells user what type of data string to enter
/// \param maxSize - maximum string size
///
/// \return ret_val - User entered string
/////////////////////////
string get_string( const string& prompt, int maxSize )
{
string ret_val;

cout << prompt;
getline(cin,ret_val);

return ret_val;
}


Entering in anything but 1 or 0 will continue the loop... I'd probably use 1 2 & 3 for the Halls instead of asking the user to enter in the name. Say..

cpp

do{

choice = get_choice("Which Hall are you staying in (0=Brown, 1=Carlton, 2=Dalton) ? ");

}while(!is_valid_choice( choice, 0, 2) );

// Add Loop to get number of weeks

// Add Loop to get tv

// Add Loop to get internet


Instead of all the if else blocks I probably use a switch statement....

cpp

switch ( choice ){
// Brown Hall
case 0: // Do calculations for Brown hall
rate = BROWN_HALL_ROOMRATE;
if( tv ) rate+= BROWN_HALL_TVRATE;
if( internet ) rate+= BROWN_HALL_INTERNETRATE;
break;

case 1: // Next hall etc....
}

total = rate * weeks;


Hope this helps...

JW



User is offlineProfile CardPM
+Quote Post

gabehabe
RE: C++ Question
2 Aug, 2008 - 02:38 PM
Post #4

Donkey DIC
Group Icon

Joined: 6 Feb, 2008
Posts: 5,539



Thanked: 98 times
Dream Kudos: 2650
Expert In: ruling the world.

My Contributions
Well that'll teach me to read the whole thing rather than scan it quickly.

Or maybe not...

Good catch, jwwicks smile.gif
User is offlineProfile CardPM
+Quote Post

rayjred
RE: C++ Question
3 Aug, 2008 - 06:06 AM
Post #5

New D.I.C Head
*

Joined: 19 Jul, 2008
Posts: 10

Thank you gabehabe and jwwicks. I'm obviously new to coding and your help and advice is certainly appreciated. icon_up.gif icon_up.gif icon_up.gif

User is offlineProfile CardPM
+Quote Post

gabehabe
RE: C++ Question
3 Aug, 2008 - 06:22 AM
Post #6

Donkey DIC
Group Icon

Joined: 6 Feb, 2008
Posts: 5,539



Thanked: 98 times
Dream Kudos: 2650
Expert In: ruling the world.

My Contributions
Just a quick note, incase you didn't already know:

When writing if statements, loops, etc, there isn't always a need for the curly braces {}

If you use one line and one line only they aren't necessary. More than anything, it's just preference, but IMO, it looks neater. However, sometimes it can be harder to understand.

cpp
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
for (int k = 0; k < 4; k++)
cout << k;

will do exactly the same as
cpp
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
for (int k = 0; k < 4; k++)
{
cout << k;
}
}
}

I just prefer to do it without using curly braces {} to save white space smile.gif

Remember though, you have to use curly braces {} if you want to execute more than one line in the if statement, example:
cpp
if (quit == true)
{ // necessary because we execute more than one thing
// in this statement
cout << "You have chosen to quit"; // one command
exit (0); // second command
} // end statement


Now I'm rambling, so I'll shut up. Let me know if that wasn't clear unsure.gif
User is offlineProfile CardPM
+Quote Post

rayjred
RE: C++ Question
8 Aug, 2008 - 01:32 PM
Post #7

New D.I.C Head
*

Joined: 19 Jul, 2008
Posts: 10

Just wanted you guys to know I did well on that last assignment. Here is what I posted. Thanks for the help. I little different from what I was told but the instructor I guess was looking for what I posted because I did well.

CODE

// asmt5rachal.cpp
// This program calculates residence fees for its students,
// internet access rates, and tv access rates.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    const double BROWN_HALL_ROOMRATE = 800.00;
    const double CARLTON_HALL_ROOMRATE = 1000.00;
    const double DALTON_HALL_ROOMRATE = 1500.00;

    const double BROWN_HALL_INTERNETRATE = 50.00;
    const double CARLTON_HALL_INTERNETRATE = 50.00;
    const double DALTON_HALL_INTERNETRATE = 80.00;

    const double BROWN_HALL_TVRATE = 20.00;
    const double CARLTON_HALL_TVRATE = 20.00;
    const double DALTON_HALL_TVRATE = 20.00;

    int student_count;
    char hall_type;
    double    weekly_room_rate,
            internet_access_rate,
            tv_access_rate,
            price_hall,
            number_of_weeks,
            room_rate,
            response,
            total_price,
            total;

    cout << setprecision(2)
         << setiosflags(ios::fixed)
         << setiosflags(ios::showpoint);
    
        // Display banner

    cout << "This program calculates residence fees for its students."
         << endl << endl;
    cout << "At each prompt, enter the requested data.";

    // Obtain input data

    cout << endl << endl << "Enter the weekly room rate:";
    cin >> weekly_room_rate;
    cout << endl << "Enter the number of weeks:";
    cin >> number_of_weeks;
    cout << endl << "Enter internet access rate (Yes or No):";
    cin.get();                        // Discard the \n
    internet_access_rate = cin.get();
    cout << endl << "Enter tv access rate (Yes or No):";
    cin.get();                        // Discard the \n
    tv_access_rate = cin.get();
    cout << endl << "Total cost: $";
    cin.get();                      // pause \n
    total = cin.get();

        //Calculate internet access

    if (internet_access_rate == 'Y' || internet_access_rate == 'y')
    {    
        total = weekly_room_rate + internet_access_rate;
    }
    else
    {
        total = weekly_room_rate;
    }
        //Calculate tv access

    if (tv_access_rate == 'Y' || tv_access_rate == 'y')
    {
        total = weekly_room_rate + tv_access_rate;
    }
    else
    {
        total = weekly_room_rate;
    }

    //Calculate total

    total = number_of_weeks * weekly_room_rate;

    // Display results

    cout << endl << endl;
    cout << "Weekly Room Rate: "     << setw(7) << weekly_room_rate << endl;
    cout << "Internet Access Rate: " << setw(7) << internet_access_rate << endl;
    cout << "TV Access Rate: "       << setw(7) << tv_access_rate << endl;
    cout << "Number Of Weeks: "      << setw(7) << number_of_weeks << endl;
    cout << "-----------------------------" << endl;
    cout << "Total:                 " << setw(7) << total << endl;
    
    // Prompt for another employee

    cout << endl << endl;
    cout << "Do you want to process another student? (Yes or No):";
    cin.get();                        // Discard the \n
    response = cin.get();

    while (response == 'Y' || response == 'y');
    
    return 0;
    
}


Thanks again. I'm going to post another assignment I'm working on to get some feed back if you guys don't mind. We are using functions in this next assignment and I'm getting errors and not sure how to fix them. I'll call the next post Functions. I want you guys to know your advice helps me more than the instructor. He doesn't tell you what you are doing wrong.
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/2/08 04:12PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month