if / else语句的输出未显示/变量赋值问题;初学程序员

时间:2017-03-03 04:56:16

标签: c++ visual-c++

我对编程很陌生,所以我对这段代码无效的原因感到困惑。例如,如果我为车辆输入"C",并为小时和分钟输入1,则会在此处停止并且不会输入if块。我知道它错过了else部分,但只是为了注意我尝试了它,但它并没有什么区别。只要我输入分钟值,程序就会达到Press any key to continue...状态。请帮忙吗?

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
    char vehicle;
    int hours, minutes;

    cout << fixed << showpoint << setprecision(2);

    cout << "If your vehicle is a car, please enter 'C'" << endl;
    cout << "If your vehicle is a truck, please enter 'T'" << endl;
    cout << "If you are a senior citizen, please enter 'S'" << endl;
    cout << "\nEnter here: ";
    cin >> vehicle;

    cout << "\nEnter the number of hours you have been parked: ";
    cin >> hours;
    cout << "\nEnter the number of minutes you have been parked: ";
    cin >> minutes;

    if (vehicle == ('C' || 'c') && minutes <= 30)
    {  
        if (hours <= 2)
        cout << "Free" << endl;
    }

    system("PAUSE");
    return 0;
}

2 个答案:

答案 0 :(得分:1)

if (vehicle == ('C' || 'c') && minutes <= 30)

没有做你认为的事情。你需要使用:

if ( (vehicle == 'C' || vehicle =='c') && minutes <= 30)

您可以将其简化为:

if ( toupper(vehicle) == 'C' && minutes <= 30)

答案 1 :(得分:0)

您的程序有逻辑错误(或者您可以说导致逻辑错误的语法错误)。

如果情况如此,你应该像这样检查大小写的车辆:

if ((vehicle == 'C' || vehicle == 'c') && minutes <= 30)

您正在检查车辆是否为&#39; C&#39;或者&#39; c&#39;但是在不知不觉中,你正在对C&#39; C进行按位操作。并且&#39; c&#39;。这些都是初学者的错误,也是学习中不可或缺的一部分。