我的程序没有返回预期的结果

C++14 My program is not returning what is expected

本文关键字:结果 返回 程序 我的      更新时间:2023-10-16
#include <stdio.h>
#include <stdlib.h>

int main()
{
    //You are in the elevator now;
    //Define variables;
    char a;
    char b;
    //Ask questions;
    printf("You are in the elevator now.nPlease enter which floor you want to visit?nPress 'L' for Basement, '1' for 1st floor, '2' for 2nd floor, and '3' for 3rd floor:n");
    scanf("%c", &a);
    //Display options;
    if (a=='L'){
        printf("You are at the basement now.n", a);
    scanf("%c", &b);
      printf("Where do you want to go?nOnly Option is 'P' for Parking lot:n");
         else (b=='P')
          printf("You are in the Parking Lot now.n", b);
    }  
    else if (a=='1')
        printf("You are at the main floor now.n", a);
    else if (a=='2')
        printf("You are at the Mechanical Department now.n", a);
    else if (a=='3')
        printf("You are at the Electrical Department now.n", a);
    else{
        printf("It's not an optionn");
    }
}

对于用户选择p后的第一个选项L,我得到的命令没有找到。我应该…你现在在停车场。我不确定是什么原因造成的。

Replace

else (b==='P')

if (b == 'P')

查看此代码…

#include <iostream>
using namespace std;
int main()
{
//You are in the elevator now;
//Define variables;
char a;
char b;
//Ask questions;
printf("You are in the elevator now.nPlease enter which floor you want to visit?nPress 'L' for Basement, '1' for 1st floor, '2' for 2nd floor, and '3' for 3rd floor:n");
scanf("%c", &a);
//Display options;
if (a=='L')
{
        printf("You are at the basement now.n");
        printf("Where do you want to go?nOnly Option is 'P' for Parking lot:n");
        cin >> b;
        if (b=='P'){
        printf("You are in the Parking Lot now.n");}
}
else if (a=='1')
    printf("You are at the main floor now.n");
else if (a=='2')
    printf("You are at the Mechanical Department now.n");
else if (a=='3')
    printf("You are at the Electrical Department now.n");
else
    printf("It's not an optionn");
return 0;
}

您可能遇到的主要问题是scanf("%c")只消耗单个字符,而在按下enter键后,您将在缓冲区中获得'n'。您可能希望以其他方式获取输入,例如使用如下命令:

std::string command;
std::cin >> command;
if (command == "P") {
    // ...
}
,因为默认情况下,它会立即加载一个完整的空白字符串。

条件语句中有三个等号

b === ' p '代替b == ' p '

相关文章: