【问题标题】:Calling a function multiple times but it prints only once多次调用一个函数但它只打印一次
【发布时间】:2021-08-05 14:28:26
【问题描述】:

我正在运行以下代码:

#include <iostream>

using namespace std;

string response(bool isMale, bool isTall)
{
    if (isMale && isTall) {
        cout << "MALE AND TALL" << endl;
    }
    else if (isMale || isTall) {
        cout << "MALE OR NOT TALL" << endl;
    }
    else {
        cout << "ELSE" << endl;
    }
}

int main()
{

    response(true, true);
    response(false, true);
    response(false, false);

    return 0;
}

输出如下:

MALE AND TALL

Process returned -1073740940 (0xC0000374)   execution time : 1.460 s
Press any key to continue.

为什么没有输出?:

MALE AND TALL

MALE OR NOT TALL

ELSE

另一个论坛帖子暗示未重置全局值。我真的不知道该怎么做。

如果有任何帮助,我将不胜感激

【问题讨论】:

  • 你答应从response()返回一个string,但你没有return任何东西。您的程序可以做任何事情,包括崩溃(就像现在一样)、什么都不做、做您想做的事情或格式化您的 C:/ 驱动器。
  • 欢迎来到未定义的行为世界,伙计!
  • 在您的构建环境中使用enable warnings 将使您受益匪浅。
  • 你告诉你的编译器编译一个返回string而不返回string的函数,不管编译器做什么,它都是对或错的

标签: c++ function output


【解决方案1】:
void response(bool isMale, bool isTall){
    if (isMale && isTall) {
        cout << "MALE AND TALL" << endl;
    }
    else if (isMale || isTall ){
        cout << "MALE OR NOT TALL" << endl;
    }
    else {
        cout << "ELSE" << endl;
    }
}

您需要将函数返回类型“string”更改为“void”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多