代码落在 if 语句上

code falling through on an if statement

本文关键字:语句 if 代码      更新时间:2023-10-16

当我添加第二个if来测试汽车尺寸M来计算TotalCarCharge然后尝试测试c的条件时,当我真正想要(68.73和148.92)时,我得到了m(77.28和167.44)的答案,几乎就像代码以某种方式落入下一个条件

测试条件

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;
}

要检查条件,您必须使用:


if (carSize == 'M')
if (carSize == 'C') .

因为当您使用该语句时:

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

并将在 if 语句中执行代码。这个条件对if (carSize = 'C')也是一样的。

或使用开关语句:

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

正如注释中指出的,您正在(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变量。

在与文本的这些比较中,一个好主意是反转操作数,如果使用单等号而不是双等数,则会引发编译器错误。

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