【问题标题】:C++14 My program is not returning what is expectedC++14 我的程序没有返回预期的结果
【发布时间】:2015-07-20 19:40:52
【问题描述】:
#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 option\n");
    }

}

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

【问题讨论】:

  • 很抱歉我多次提出问题
  • 我的电脑有问题
  • 你为什么一直添加随机编辑?
  • 抱歉系统不让我上传问题
  • 您的随机缩进使您的代码难以阅读。第二个scanf 和它下面的printf 应该缩进,并且所有内容都应该对齐。

标签: c++ c++14


【解决方案1】:

替换

else (b==='P')

通过

if (b == 'P')

【讨论】:

  • 更好的是,还要添加花括号。
【解决方案2】:

检查此代码...

#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 option\n");
return 0;
}

【讨论】:

  • @Karthik Chowdary 用户输入L再输入P后,编译器显示P commands not found
【解决方案3】:

您可能遇到的主要问题是scanf("%c") 仅使用一个字符,并且在您按下回车键后,您将在缓冲区中有一个'\n'。您可能希望以其他方式获取您的输入,例如使用以下方式:

std::string command;
std::cin >> command;
if (command == "P") {
    // ...
}

因为默认情况下,它会一次加载整个以空格分隔的字符串。

【讨论】:

    【解决方案4】:

    条件语句中有三个等号。

    b === 'P' 而不是 b == 'P'

    【讨论】:

    • 感谢您的帮助
    • 我认为问题在于你的 if 块的结构。如果用户选择“L”,他们别无选择,只能选择“P”;因此,您不需要 else 语句来测试 b。尝试单独的 if 语句。
    猜你喜欢
    • 1970-01-01
    • 2016-06-28
    • 2015-09-16
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多