【问题标题】:How can I make my function bring back true or false我怎样才能让我的功能带回真或假
【发布时间】:2013-10-09 08:40:39
【问题描述】:

我是 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;
        }
    }
}

请帮忙!提前致谢!

【问题讨论】:

标签: c++ function return-value


【解决方案1】:

要将布尔值格式化为truefalse,您可以使用std::boolalpha 操纵器设置std::ios_base::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
}

【讨论】:

  • 如果程序的目的是教育,输入验证会掩盖实际代码。
  • @riv:如果人们不学习如何正确读取数据,他们永远不会检查!不检查示例代码是个坏主意:我看到太多生产代码没有检查成功输入。
  • 大家好,感谢所有建议,我现在可以让函数返回文本!
猜你喜欢
  • 2012-04-29
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
  • 1970-01-01
  • 2014-08-14
  • 1970-01-01
相关资源
最近更新 更多