【问题标题】:Conditional statement outputting the wrong command [closed]输出错误命令的条件语句[关闭]
【发布时间】:2020-01-08 21:21:51
【问题描述】:

这里是初学者,如果我犯了nooby错误,我很抱歉 我将 di 分配为数组 myworld[] ,具体取决于用户输入,它会将 di 分配到适当的数组位置,但由于某种原因,当我的输入为 'c 时,if 语句会继续输出“make”而不是“change” '

我尝试删除 else if 并将 if 用于所有这些,或者摆脱 else if 并仅使用 else。

#include <iostream>
using namespace std; 

int main() {

char di;
char myword[] = {'d','m','s' ,'c'};
do {
    cout << "Make a selection:" << endl;
    cout << "d - insert 1$ bill" << endl; 
    cout << "m - view menu" << endl; 
    cout << "s - select an item" << endl; 
    cout << "c - get change" << endl; 
    cin >> di;
    if (di == 'd')
        di = myword[0];
    else if (di == 'c')
        di = myword[3]; 
}while (!myword);

if (myword[0])
    cout << "make";
else if (myword[3])
    cout << "change";
return 0;
}

【问题讨论】:

  • 提示:myword[0] 会评估什么? !myword 会是真的吗?您在这里想要的可能是switch 声明。
  • 首先,纠正你的缩进,因为它看起来有点混乱。你想用那个 do while 循环来实现什么。你想要多个输入吗?如果是这样,您需要一个类型来实际保存这些值。您可以查看 C++ 容器类型,例如向量。例如。 std::vector&lt;char&gt; vec; vec.push_back( di );然后检查存储在vec中的所有输入

标签: c++ arrays loops conditional-statements


【解决方案1】:

可能你忘记在 if 语句中进行比较了。现在你只是说if('d'!= 0) 这总是正确的。也许你试图让if(di == myword[0])else if 语句也是如此。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多