gpt4 book ai didi

c++ - 我怎样才能让我的函数返回 true 或 false

转载 作者:行者123 更新时间:2023-11-28 07:23:08 24 4
gpt4 key购买 nike

我是 C++ 的新手,我真的被这个问题困住了:当用户输入 2 个数字 EX:1 和 2 时,代码必须弄清楚第一个数字是否比第一个数字大,问题是代码不会像它带来的文本那样带来真或假作为数字:/(0=假 1=真)

代码在这里:

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

bool GraterFunct(int num1, int num2);

int main(int argc, char** argv)

{
std::cout <<" \n Hello there! This is a test to test how good you are with math. \n ";
std::cout <<" Now enter G or L (Grater, less) to know if a number is grater or less than the number you choose \n ";
char answer [1];
std::cin >> answer;

if(answer == "G" || "g")
{
int number1;
int number2;
std::cout << "You selected: Grater than, \n";
std::cout << "Now type 2 numbers and see which one is grater than the other one. \n" << std::endl;
std::cin >> number1;
std::cout << "Your first number: " << number1 << std::endl;
std::cout << "Select your second number \n";
std::cin >> number2;
std::cout << "The answer is: " << GraterFunct(number1, number2);
}

return 0;
}

bool GraterFunct(int num1, int num2)
{
if(num1 >= num2)
{
{
return true;
}
}
else
{
if(num2 >= num1)
{
return false;
}
}
}

求助!提前致谢!

最佳答案

要将 bool 值格式化为 truefalse,您可以使用 std 设置 std::ios_base::boolalpha 标志::boolalpha 操纵器:

std::cout << std::boolalpha << "true=" << true << " false=" << false << '\n';

如果您像我一样不是以英语为母语的人,您可能想要更改这些值的格式。假设安装了合适的语言环境,您可以将 imbue() 放入流中,或者您可以使用 truefalse 的任何渲染创建自己的语言环境你想要,例如:

#include <iostream>
#include <locale>

class numpunct
: public std::numpunct<char>
{
std::string do_truename() const { return "wahr"; }
std::string do_falsename() const { return "falsch"; }
};

int main()
{
std::cout.imbue(std::locale(std::locale(), new numpunct));
std::cout << std::boolalpha << "true=" << true << " false=" << false << '\n';
}

顺便说一句,您总是需要验证您的输入是否成功,例如:

if (std::cin >> number1) {
// deal with the successful input here
}
else {
// deal with the wrong input here
}

关于c++ - 我怎样才能让我的函数返回 true 或 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19145810/

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