c ++编译器忽略第一个if语句

时间:2014-03-11 04:36:03

标签: c++ visual-c++ if-statement visual-studio-2010-beta-2

我在这是一个新手,正在研究我的拳头if / else程序。我无法获得第一个if语句来识别我输入的“r”。我尝试只用一个声明,我能够输入老师给我们的所有输入的例子,用于住宅和商业。但是,当我完全运行程序时,我遇到了问题。我选择R代表住宅,0代表额外连接,0代表付费频道,而不是18.50美元的产出我获得75.00美元的商业费用。我确信这是一个简单的错误,但我无法弄清楚我做错了什么。知道如何使用if / else的人可以给我一些见解!

#include "stdafx.h"
#include <conio.h>
#include <iostream>
#include <iomanip>
using namespace std;

int main()

{
    const float BASIC_RESIDENTIAL   =   18.50;
    const float BASIC_BUSINESS      =   75.00;
    const float CONNECT_RESIDENTIAL =   6.50;
    const float CONNECT_BUSINESS    =   5.00;
    const float PREMIUM_RESIDENTIAL =   7.50;
    const float PREMIUM_BUSINESS    =   50.00;


    char    customerType;
    int     numOfConnections;
    int     numOfPremiumChannels;
    float   amountCableBill;

    cout << fixed << setprecision(2);
    cout << "Residential or Business [R or B]?   ";
    cin  >> customerType;
    cout << endl << endl;
    cout << "How many Additional Connections?    ";
    cin  >> numOfConnections;
    cout << endl << endl;
    cout << "Total number of Premium Channels:   ";
    cin  >> numOfPremiumChannels;
    cout << endl << endl;


    if (customerType == 'R' || customerType == 'r')
    {
        amountCableBill = BASIC_RESIDENTIAL + CONNECT_RESIDENTIAL * numOfConnections +       PREMIUM_RESIDENTIAL * numOfPremiumChannels;
    }
    //else customerType == 'B' || customerType == 'b';   // unnecessary
    {
        if (numOfConnections <= 9)

            amountCableBill = BASIC_BUSINESS + PREMIUM_BUSINESS * numOfPremiumChannels;

        else
            amountCableBill =  BASIC_BUSINESS + (numOfConnections - 9) * CONNECT_BUSINESS + PREMIUM_BUSINESS *numOfPremiumChannels;
    }

    cout << "Total amount of Cable Bill:  "  << amountCableBill << endl << endl;
    cout << "Press <ENTER> to end..." << endl;



    _getch();

    return 0;
}

2 个答案:

答案 0 :(得分:1)

虽然条件else if (customerType == 'B' ...)可能是多余的,但您仍然需要在分支的左括号前放置else

这是

if (condition) { code } else { code }

答案 1 :(得分:1)

else中需要condition(除非您希望每次都执行“some other code”)

if (customerType == 'R' || customerType == 'r')
{
   //Some Code
}
else  //<--Notice else
{
   //Some other code.
}