用c ++中的两个char变量评估boolean

时间:2017-09-30 19:14:15

标签: c++

道歉,这里有点初学者:

我正在制定练习计划,以确定基于一天中的小时和一周中的某一天的长途电话费用......我已经接受了我的do-while循环并尝试使用嵌套工作日与周末分开。

然而,当我编译并运行时,无论是否插入对应于我试图评估的布尔值的Chars,都会跳过if和else if嵌套语句。我很难理解我在这里缺少的东西。指示清楚地说明一周的日期应该存储在两个字符变量中:Mo Tu We Th Fr Sa Su。

do
{
    //have user input day of week of call
    printf("\nOn what day was the call made? (Mo, Tu, We, Th, Fr, Sa, or Su) ");
    scanf("%c%c", &day1, &day2);

    //branch for weekday vs weekend vs invalid input
    if (((day1 == 'M') && (day2 == 'o')) || ((day1 == 'T') && (day2 == 'u')) || ((day1 == 'W') && (day2 == 'e')) || ((day1 == 'T') && (day2 == 'h')) || ((day1 == 'F') && (day2 == 'r')))
    {
        //determine if phone call was made at hi or low rate times
        printf("At what time was your call made? (HH MM - with 08 00 representing 8:00 AM and 18 30 representing 6:30 PM) ");
        scanf("%f %f", &call_time_hour, &call_time_minute);
        call_time_hour = call_time_hour + (call_time_minute / 60);

        printf("%f", call_time_hour);
    }
    else if (((day1 == 'S') && (day2 == 'a')) || ((day1 == 'S') && (day2 == 'u')))
    {
        printf("What was the duration of your call? ");
        scanf("%d", &call_duration);

        //calculate total cost of call
        cost_of_call = call_duration * 0.15;

        printf("%s %.2lf", "The cost of this call was $", cost_of_call);
    }
    calls_made--;
    printf("%d", calls_made);
}while (calls_made > 0);

因此,例如,当我编译并运行程序并在调用的那一天输入“Sa”时,它会直接转到'calls_made--'步骤。

1 个答案:

答案 0 :(得分:0)

问题在于之前的scanf。调试并查看真正扫描的字符。我确信day1将是'\n'

在这种情况下,在扫描星期几之前清除输入流:

while (getchar() != '\n');