gpt4 book ai didi

c++ - 将 bool 值传递给另一个无法正常工作的函数?

转载 作者:搜寻专家 更新时间:2023-10-31 02:04:27 25 4
gpt4 key购买 nike

C++ 的新手,才接触了几天。我正在尝试编写一个简单的控制台计算器,要求用户输入 Y 或 N 以确认打印的结果实际上是正确的。

我调用了一个函数,该函数请求用户输入一个字符表示 Y/N,然后根据输入的内容将其作为 boolean 值返回为 true 或 false。然后它返回到带有那个 bool 的 main,然后它被传递到另一个函数,该函数根据传递的是 true 还是 false 来打印文本。但是,每当我运行该程序时,它总是打印 true 和 false 的语句。我确定我在使用 bool 时违反了某种规则,或者存在某种小错误,但我似乎无法找到它。任何帮助将不胜感激。

bool getConfirmation()
{
std::cout << "Is this result correct? Y/N: ";
char confirm;
std::cin >> confirm;
if (confirm == 'Y', 'y') return true;
if (confirm == 'N', 'n') return false;
else return false;
}

void confirmResult(bool confirm)
{
if (confirm == true)
std::cout << "Result is correct.";
if (confirm == false)
std::cout << "Sorry, please try again.";
else
std::cout << "Sorry, please try again.";
}

int main()
{
std::cout << "Please input the first integer: ";
int x{ getInteger() };
std::cout << "Please input the desired operation: ";
char op{ getOperation() };
std::cout << "Please input the second integer: ";
int y{ getInteger() };
int result{ calculateResult(x, op, y) };
printResult(result);
bool confirm{ getConfirmation() };
confirmResult(confirm);
return 0;
}

最佳答案

confirm == 'Y', 'y'不按您的想法行事 - 这是一个包含内置逗号运算符表达式,它的计算结果始终为'y'。 .正确的代码是:

confirm == 'Y' || confirm == 'y'

你总是会看到两者

  • std::cout << "Result is correct.";

  • std::cout << "Sorry, please try again.";

正在执行,因为您的 boolean 逻辑不正确。

if (confirm == true)
A
if (confirm == false)
B
else
C

如果confirm == true ,那么 A 和 C 都将被执行,作为第二个 if else 没有引入语句.你的逻辑应该是:

if (confirm == true)
std::cout << "Result is correct.";
else
std::cout << "Sorry, please try again.";

关于c++ - 将 bool 值传递给另一个无法正常工作的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53487649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com