代码落在if语句上

时间:2014-02-14 05:15:17

标签: c++

当我添加第二个如果测试汽车大小M到calculateTotalCarCharge然后尝试测试c的条件,我得到m(77.28& 167.44)的答案我真的想要(68.73& 148.92) ,它几乎就像代码以某种方式进入下一个条件

测试条件

Type - Days - Amount
C - 3 - 68.73
M - 3 - 77.28
C - 7 - 148.92
M - 7 - 167.44


#include <iostream> //for I/O
#include <iomanip> //for formatting output
#include <cmath>    //for math


using namespace std;

//prototypes
char validateCarChoice();
void displayProgramDescription();
int validateNumEntry(string prompt);
double calculateTotalCarCharge (char carSize, int daysRented);


//global constants
const char COMPACT = 'C';
const char MID = 'M';
const char FULL = 'F';
const char SUV = 'S';
const double COMPACT_DAILY_CHARGE = 22.91;
const double MID_DAILY_CHARGE = 25.76;
const double FULL_DAILY_CHARGE = 28.87;
const double SUV_DAILY_CHARGE = 98.88;

// --------------------------------------------------------------------------
// Description:
// Input parameter:
// Returns:
// ---------------------------------------------------------------------------

int main() 
{
    //local constants
    const string ENTER_DAYS_RENTED = "Enter the number of days rented: ";
    const string ENTER_MILES_DRIVEN = "Enter number of miles driven: ";

    //local variables
    char userCarTypeChosen;
    char carSize;
    int daysRented;
    double milesDriven;
    double carCharge;


//call function to display program description
displayProgramDescription();

//calls function to validate the car choice input by user
userCarTypeChosen = validateCarChoice();

//if car type chosen is suv (S) then only prompt will be to enter days
//rented, if not prompt both days rented and miles driven.
if (userCarTypeChosen == 'S')
{
    daysRented = validateNumEntry(ENTER_DAYS_RENTED);
}
else
{   
    daysRented = validateNumEntry(ENTER_DAYS_RENTED);
    milesDriven = validateNumEntry(ENTER_MILES_DRIVEN);
}

carCharge = calculateTotalCarCharge(carSize, daysRented);

   //to be removed
cout << carCharge;

    return 0;
}

// --------------------------------------------------------------------------
// Description: displayProgramDescription - displays program description
// Input parameter: N/A
// Returns: N/A
// ---------------------------------------------------------------------------

void displayProgramDescription()
{
    //local constant
    const string PROGRAM_DESCRIPTION = "This program will calculate a car rental"
    " bill for Rent2U.";

    //displays program description
    cout << PROGRAM_DESCRIPTION << endl;    
}

// --------------------------------------------------------------------------
// Description: validateCarChoice - displays menu of car options and daily cost.
//              Then error checks that a valid choice was given
// Input parameter: N/A
// Returns: letter of car chosen
// ---------------------------------------------------------------------------

char validateCarChoice ()
{
    //local constants

    const string ENTER_CAR_LETTER = "Enter letter for car size rented: ";
    const string ERROR_CAR_INPUT = "Re-enter letter for car size rented: ";

    //local variable
    char carSize;

    //displays car size options

    cout << "Car sizes:" << endl << endl;
    cout << setw(5) << "C - Compact size at $ 22.91 per day" << endl;
    cout << setw(5) << "M - Mid size at $ 25.76 per day" << endl;
    cout << setw(5) << "F - Full size at $ 28.76 per day" << endl;
    cout << setw(5) << "S - SUV at $ 98.88 per day" << endl << endl;

    //prompt for user input
    cout << ENTER_CAR_LETTER;
    cin >> carSize;
    carSize = toupper(carSize);

    //validation of car type chosen
    while (carSize !='C' && carSize !='M' && carSize !='F' && carSize !='S')
    {
  cout << ERROR_CAR_INPUT;
  cin >> carSize;
  carSize = toupper(carSize);       
    }

    return carSize;
}

// --------------------------------------------------------------------------
// Description: validateNumEntry - validates that the user entry is at least 1
// Input parameter: prompt- prompts user to enter number
// Returns: the user inputed number
// ---------------------------------------------------------------------------

int validateNumEntry (string prompt)
{
    //local constant
    const string ERROR = "Error - entry must be at least 1.";

    //local variable
    double num;

    cout << prompt;
    cin >> num;


    while (num < 1)
    {
        cout << ERROR << endl;
        cout << prompt;
        cin >> num; 
    }

    return num;
}

// --------------------------------------------------------------------------
// Description:
// Input parameter:
// Returns:
// ---------------------------------------------------------------------------

double calculateTotalCarCharge (char carSize, int daysRented)
{
    //local constant
    const int WEEK = 7;
    const double LOWER_WEEK_RATE = 6.5;

    //local variable
    double totalCarCharge;
    int wholeWeek;
    int extraDays;


    if (carSize = 'C')
    {
        if (daysRented < WEEK)
        {
            totalCarCharge = (COMPACT_DAILY_CHARGE * daysRented);
        }
        else
        {
            wholeWeek = (daysRented / WEEK);
            extraDays = (daysRented % WEEK);
            totalCarCharge = ((wholeWeek * LOWER_WEEK_RATE * 
            COMPACT_DAILY_CHARGE) + (extraDays * COMPACT_DAILY_CHARGE));
        }
    }

    //once i add this if condition, if I try and test C I get the calculations
    //for M
    if (carSize = 'M')
    {
        if (daysRented < WEEK)
        {
            totalCarCharge = (MID_DAILY_CHARGE * daysRented);
        }
        else
        {
            wholeWeek = (daysRented / WEEK);
            extraDays = (daysRented % WEEK);
            totalCarCharge = ((wholeWeek * LOWER_WEEK_RATE * MID_DAILY_CHARGE) 
            + (extraDays * MID_DAILY_CHARGE));
        }
    }

    return totalCarCharge;
}

3 个答案:

答案 0 :(得分:1)

正如评论中指出的那样,您将在(carSize = 'C') and (carSize = 'M')中的if语句中进行分配。出于兴趣,为什么不在这里选择switch字符?分支似乎是互斥的,你不是在分支中变异carSize?这可能有助于避免将来出现此类问题:

switch (carSize)
{
    case 'C':
       if (daysRented < WEEK)
        ...
       break;
    case 'M':
       // ...
 }

修改

您的代码中存在第二个错误,即您正在分配:

userCarTypeChosen = validateCarChoice();

但是你将未初始化的变量carSize传递给calculateTotalCarCharge函数:

carCharge = calculateTotalCarCharge(carSize, daysRented);

您应该将作业更改为carSize

carSize = validateCarChoice();

然后完全删除userCarTypeChosen变量。

答案 1 :(得分:1)

对于检查条件,您必须使用:

if (carSize == 'M')

if (carSize == 'C')

因为当你使用语句时:

if (carSize = 'M')只会将值carSize分配给'M'

并将在if语句中执行代码。 这个条件也适用于if (carSize = 'C')

或者使用switch语句:

switch (carSize)
{
    case 'C':
       if (daysRented < WEEK)
        ...
       break;
    case 'M':
       // ...
 }

答案 2 :(得分:0)

在对文字的这些比较中,一个好主意可以是反转操作数,如果使用单个等于而不是双等,则会抛出编译器错误。

if (var == 'C')  // compiles, runs correctly
if (var = 'C')   // compiles, runs incorrectly, results in stackoverflow question
if ('C' == var)  // compiles, runs correctly
if ('C' = var)   // does not compile, fix this problem immediately